【发布时间】:2019-01-21 06:11:07
【问题描述】:
我的代码由两个进程组成。父进程不断地从标准输入读取单个字符并写入管道(无需按 ENTER)。子进程从管道读取并写入标准输出。我的父进程成功写入管道,但子进程没有打印输出。
子进程没有打印输出的原因是它卡在父进程的while循环中,永远不会进入子进程的while循环。
当我在我的 Mac 上使用活动监视器强制退出父进程时,我输入的内容实际上会被打印出来。紧随其后的是“Killed:9”
有没有办法修复我的代码,以便每次父(输入)接收到一个字符时,子(输出)打印出每个字符,而不会卡在父进程的 while 循环中?
char input() {
char input = getchar();
return input;
}
int main(void) {
int inputOutputFd[2];
pid_t childpid = 0;
system("/bin/stty raw igncr -echo");
if(pipe(inputOutputFd) < 0) {
perror("Failed to create pipe");
return 1;
}
if((childpid = fork()) == -1) {
perror("Failed to fork input child");
return 1;
}
//parent's code -INPUT
if (childpid > 0) {
close(inputOutputFd[0]);
printf("Please enter a word or phrase");
while(1) {
char inputChar = input();
write(inputOutputFd[1], &inputChar, sizeof(inputChar));
}
close(inputOutputFd[1]);
wait(NULL);
} else {
//child -OUTPUT
char outputChar;
close(inputOutputFd[1]);
while (read(inputOutputFd[0], &outputChar, sizeof(outputChar)) > 0)
{
printf("%c", outputChar);
fflush(stdin);
}
} //END OF IF-ELSE LOOP
}//END MAIN
【问题讨论】:
-
The reason the child process isn't printing out the output is because it's stuck in the while loop of the parent process and never enters the child process's while loop.嗯?你确定?它甚至没有进入父级的while循环。 -
它确实进入了父级的 while 循环。我在父级的 while(1) 循环中添加了一个 printf()。我去掉了所有那些 printf 语句,这样代码看起来不那么混乱了。
-
是的,父母进入了父母的while循环,但孩子没有。
-
为什么孩子需要进入父母的while循环?这是另一个过程。它只需要从父写入的管道中读取。
-
不需要也不需要。我很困惑。 你说它进入了父while循环,但它没有。或者我只是误解了我在最初评论中引用的那句话。
标签: c linux operating-system