我在一个C程序中,我正在使用fork()系统调用来创建子进程。如何从子代->父代传递一个值?子进程的退出代码是否可以在父进程中的某个位置检索到?谢谢
发布于 2011-03-20 20:53:46
您可能对wait()和waitpid()感兴趣,请参阅http://linux.die.net/man/2/waitpid
下面是一个使用waitpid()的非阻塞示例:
pid_t child;
int child_status, status;
switch(child = fork()) {
case 0:
/* child process */
do_silly_children_stuff();
exit(42);
case -1:
/* fork() error */
do_some_recovery();
break;
default:
/* parent process */
do_parenting_stuff();
break;
}
// busy-wait for child to exit
for (;;) {
status = waitpid(child, &child_status, WNOHANG);
switch (status) {
case -1:
/* waitpid() error */
break;
case 0:
/* child hasn't exited yet */
break;
default:
/* child with PID $child has exited with return value $child_status */
break;
}
}请注意,我没有测试上面的代码。
对于一般的异步进程间通信,您可以使用管道( pipes ())、套接字、共享内存或小心文件。
发布于 2011-03-20 20:56:17
在父进程中使用waitpid(pid)。
pid_t waitpid(pid_t pid, int *status, int options);描述
waitpid函数挂起当前进程的执行,直到pid参数指定的子进程已经退出,或者直到传递了一个信号,该信号的操作是终止当前进程或调用信号处理函数。如果pid请求的子进程在调用时已经退出(所谓的“僵尸”进程),该函数将立即返回。子进程使用的任何系统资源都会被释放。
http://linux.about.com/library/cmd/blcmdl2_waitpid.htm
https://stackoverflow.com/questions/5368591
复制相似问题