我正在尝试从父进程的子进程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[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;
}
child.c
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:
,但是当我尝试输入内容时,即使按下回车键也不会显示任何内容。
你知道我该如何使它工作?
谢谢你的帮助。
在家长中,不要等到孩子读完管道之前完成。它可能在这种情况下工作,因为你可能没有足够的写入来填充管道缓冲区,但是如果它被填充,那么作者将会阻塞,并且你有一个死锁。 –
另外,你有什么版本的'gets'函数需要缓冲区大小?你在使用'gets_s'的一些变体吗? –
您的父母计划还存在其他一些问题。例如,它不应该干净地编译。 –