我的作业有问题。
在父进程终止后,我必须从子进程中的终端读取数据。写得很清楚,父进程必须在执行子进程后立即死亡,因此我找到的解决方案(例如使用 wait()
)对我来说没有用。
我的代码
int main(void)
{
printf("start main\n");
if(fork() == 0){
char buffer[64];
fgets(buffer, 64, stdin);
printf("Child process: %s\n", buffer);
}
else printf("end main\n");
//Using WAIT() here is not allowed in my assignment.
return 0;
}
它不会等待我输入数据。看来父进程结束后,子进程处于后台,无法从终端读取任何数据。
结果
damian@damian-Virtualbox:-$ ./testuje
start main
end main
damian@damian-Virtualbox:-$ Child Process:
echo test | ./testuje
start main
end
damian@damian-Virtualbox:-$ Child Process: test
程序应该做什么
print: start main
print: end main
then it should:
wait for user to type something
print: child process: text_typed_by_user
编辑:建议我使用 tee
命令。你知道如何用它来实现我想要的吗?
最佳答案
您可能想使用 vfork
而不是 fork
(检查 documentation here ):
pid_t vfork(void);
vfork - create a child process and block parent
关于c - 在子进程中读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34826761/