【发布时间】:2014-06-03 02:39:30
【问题描述】:
我正在编写一个由父母和他的孩子组成的 C 程序(使用 fork)。他们通过管道进行通信。父通过标准输出写入管道,子通过标准输入从管道读取。一旦它们连接起来,父母将“hello world”写入管道,儿子调用exec。我的代码如下所示:
int main(int argc, char *argv[])
{
int p, a;
char buf[1024];
FILE *file;
size_t nread;
int fd[2];
char argument[PATH_MAX];
if(pipe(fd)<0){
return 1;
}
p = fork();
switch(p){
case -1: perror("Error en el fork()"); return 1;
case 0:
close(fd[1]);
close (0);
dup(fd[0]);
close(fd[0]);
sprintf(argument,"/usr/bin/%s",argv[1]);
execvp(argument,argv);
perror("Error en el execv");
exit(1);
default: break;
}
close(fd[0]);
close(1);
a = dup(fd[1]);
close(fd[1]);
write(1,"Hello World\n",12);
close(a);
wait(NULL);
return 0;
}
子执行的exec函数调用函数rev或wc。如果不带参数调用,rev 和 wc 应该应用于标准输入(在我的例子中是“hello world”)。但这不起作用,我不知道为什么。任何帮助将不胜感激。
【问题讨论】:
-
父亲仍在写入
1而不是写入a,而孩子没有从管道读取。