[英]How can the child process read stdout from the pipe and the parent process write stdin to the pipe?
[英]How to pipe stdin from child to parent?
我正在尝试从父进程exec()
子进程。 在这个子流程中,我要求用户输入一条消息,以便可以由父流程将其打印出来,但是我找不到解决方法...
到目前为止,我的代码是:
父母
int main(int argc, char **argv) {
int fd[2];
char line[80];
pipe(fd);
pid_t pid = (pid_t)fork();
if(pid > 0) {
waitpid(pid, NULL, 0);
close(fd[0]);
int size = read(fd[1], line, 79);
close(fd[1]);
line[size] = '\0';
printf("[parent] Received \"%s\", size = %d\n", line, size);
}
else {
close(fd[1]);
close(stdin);
dup2(fd[0], stdin);
close(fd[0]);
exec("./child", 0, NULL);
}
return 0;
}
小孩
int main(int argc, char **argv) {
char line[80];
printf("[child] Enter message: ");
gets(line, 80);
printf("[child] line = %s\n", line);
return 0;
}
当我启动父进程时,它显示[child] Enter message:
但是,当我尝试键入某些内容时,即使按了回车键,也没有任何显示。
你知道我该怎么做吗?
谢谢您的帮助。
除了我的评论中提到的问题之外,您遇到的问题还很僵局 。 之所以会这样,是因为父进程等待子进程退出。 但是子进程正在等待永远不会到达的输入。
这是因为在子进程中,您说输入应来自pipe 。
此外,在父进程中,您尝试从管道的写端读取 。
最后,只要子进程想要读取用户输入,您的程序将永远无法运行,因为所有用户输入都将进入父进程。
为了使其全部正常工作,您需要重新考虑设计,并使父进程成为从用户读取输入并写入管道的进程。 并且子进程应从管道读取并打印到(非管道)标准输出。 或者关闭父级中的(普通,非管道)标准输入,然后在子级中写入管道(作为标准输出)。
您的代码有几个问题:
pipe
获得的描述符的顺序 这是一个固定版本(我通过fgets更改了gets,并使用execl更改了您的exec以使所有内容都可以编译):
parent.c:
int main(int argc, char **argv) {
int fd[2];
char line[80];
pipe(fd);
pid_t pid = (pid_t)fork();
if(pid > 0) {
waitpid(pid, NULL, 0);
close(fd[1]);
int size = read(fd[0], line, 79);
close(fd[0]);
line[size] = '\0';
printf("[parent] Received \"%s\", size = %d\n", line, size);
}
else {
close(fd[0]);
close(1);
dup2(fd[1], 1);
close(fd[1]);
execl("./child", NULL);
}
return 0;
}
小孩
int main(int argc, char **argv) {
char line[80];
fprintf(stderr, "[child] Enter message: ");
fgets(line, 80, stdin);
printf("[child] line = %s\n", line);
return 0;
}
我找到了一种解决方法。 我的实际目标是在父母与孩子之间传递信息。 我的错误是在stdin
上的dup2
。 这样,程序询问时我什么也输入不了。 因此,我在argv
传递了文件描述符的值,问题就解决了。
再次感谢你的帮助 !
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.