简体   繁体   English

我的子进程无法使用 Pipe 从父进程接收最后一个值

[英]My child process cannot receive the last value from parent process using Pipe

in my program, child process should receive some value from keyboard, and send to parent process.在我的程序中,子进程应该从键盘接收一些值,然后发送给父进程。 Parent process should calculate the sum and return to child process.父进程应该计算总和并返回到子进程。 My program is shown below:我的程序如下所示:

3 4 5 -1 child(4753): Sending 3 to parent Parent(4751): Received 3 Parent(4751): Sending 3 back Parent(4751): Received 4 Parent(4751): Sending 7 back Parent(4751): Received 5 child(4753): Received 3 Parent(4751): Sending 12 back Parent(4753): Received 4 Parent(4753): Sending 7 back Parent(4753): Received 5 Parent(4753): Sending 12 back 3 4 5 -1 child(4753): Sending 3 to parent Parent(4751): Received 3 Parent(4751): Sending 3 back Parent(4751): Received 4 Parent(4751): Sending 7 Parent(4751): Received 5 child(4753): 收到 3 Parent(4751): 发回 12 Parent(4753): 收到 4 Parent(4753): 发回 7 Parent(4753): 收到 5 Parent(4753): 发回 12

From the result, the last step is Parent send 12 back but child cannot received 12 and show the total sum.从结果来看,最后一步是父发回 12 但子不能收到 12 并显示总和。 Therefore, anyone has some ideas why the result is not my expected and how to modify my code?因此,任何人都有一些想法为什么结果不是我的预期以及如何修改我的代码?

Thanks in advance.提前致谢。

Your parent process just runs to an end without waiting for the child to finish.您的父进程只是运行结束,而无需等待子进程完成。 Thus the child is killed before it can actually print a result.因此,孩子在实际打印结果之前就被杀死了。

You need to add a wait() or waitpid() in the proper place of the parent process.您需要在父进程的适当位置添加wait()waitpid()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM