父子进程使用管道通信,在 "execlp" 后挂起,为什么?
Father-child process use pipe to talk, hangs after "execlp", why?
我在当前目录下有一个名为"tmp"的简单文本文件,我想"cat"这个文件然后"sort"它,我想用一个c程序来执行像管道“|”所以我尝试使用 father/child 谈话来做到这一点。
没想到,程序在"cat"之后挂了,如下图:
#include<stdlib.h>
#include<stdio.h>
#include<unistd.h>
int main(){
int pipefd[2];
pipe(pipefd);
int& readfd=pipefd[0];
int& writefd=pipefd[1];
pid_t pid=fork();
if(pid==0){//child
dup2(STDIN_FILENO,writefd);
close(readfd);
execlp("cat","cat","tmp",NULL);
printf("child cat ends\n");
exit(0);
}else{//father
dup2(STDOUT_FILENO,readfd);
close(writefd);
execlp("sort","sort",NULL);
printf("father sort ends\n");
}
int status;
wait(&status);
printf("father exists\n");
return 0;
}
g++ 编译和 运行 这个文件,在 "cat" tihis 文件之后,我什至没有看到 "child cat ends",它只是挂起。
问题出在哪里,如何解决?
谢谢
1) dup2 中的参数顺序不正确。看看dup2
2) dup2 的参数 (stdin/stdout) 不正确。
3) exec() 系列函数用新的过程图像替换了过程图像。所以那个调用之后的代码不会到达 运行 (除非 exec() 失败),所以我删除了那些。
代码如下:
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
int main(){
int pipefd[2];
pipe(pipefd);
int& readfd = pipefd[0];
int& writefd = pipefd[1];
pid_t pid = fork();
if(pid == 0){ //child
dup2(writefd, 1); // 1 is STDOUT_FILENO -- cat already has input -- needs output
close(readfd);
execlp("cat","cat","tmp.txt", NULL);
perror("execlp() failed in child");
}else{ //father
dup2(readfd, 0); // 0 is STDIN_FILENO -- because sort needs input!
close(writefd);
execlp("sort","sort", NULL);
perror("execlp() failed in parent");
}
return 0;
}
我在当前目录下有一个名为"tmp"的简单文本文件,我想"cat"这个文件然后"sort"它,我想用一个c程序来执行像管道“|”所以我尝试使用 father/child 谈话来做到这一点。
没想到,程序在"cat"之后挂了,如下图:
#include<stdlib.h>
#include<stdio.h>
#include<unistd.h>
int main(){
int pipefd[2];
pipe(pipefd);
int& readfd=pipefd[0];
int& writefd=pipefd[1];
pid_t pid=fork();
if(pid==0){//child
dup2(STDIN_FILENO,writefd);
close(readfd);
execlp("cat","cat","tmp",NULL);
printf("child cat ends\n");
exit(0);
}else{//father
dup2(STDOUT_FILENO,readfd);
close(writefd);
execlp("sort","sort",NULL);
printf("father sort ends\n");
}
int status;
wait(&status);
printf("father exists\n");
return 0;
}
g++ 编译和 运行 这个文件,在 "cat" tihis 文件之后,我什至没有看到 "child cat ends",它只是挂起。
问题出在哪里,如何解决? 谢谢
1) dup2 中的参数顺序不正确。看看dup2
2) dup2 的参数 (stdin/stdout) 不正确。
3) exec() 系列函数用新的过程图像替换了过程图像。所以那个调用之后的代码不会到达 运行 (除非 exec() 失败),所以我删除了那些。
代码如下:
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
int main(){
int pipefd[2];
pipe(pipefd);
int& readfd = pipefd[0];
int& writefd = pipefd[1];
pid_t pid = fork();
if(pid == 0){ //child
dup2(writefd, 1); // 1 is STDOUT_FILENO -- cat already has input -- needs output
close(readfd);
execlp("cat","cat","tmp.txt", NULL);
perror("execlp() failed in child");
}else{ //father
dup2(readfd, 0); // 0 is STDIN_FILENO -- because sort needs input!
close(writefd);
execlp("sort","sort", NULL);
perror("execlp() failed in parent");
}
return 0;
}