开发者

Parent-child process communication

I am in a C program and I am using a fork() system call in order to create a chi开发者_如何学Gold process. How can I transmit a value from child->parent ? Could the exit code of the child be retrieved somewhere in the parent process? .. Thank you


You might be interested in wait() and waitpid(), see http://linux.die.net/man/2/waitpid

Here's a non-blocking example of using 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;

        }
}

Note that I didn't test the above code.

For general asynchronous inter-process communication, you can use pipes (pipe()), sockets, shared memory or - beware - files.


Use waitpid(pid) in the parent process.

pid_t waitpid(pid_t pid, int *status, int options);

DESCRIPTION

The waitpid function suspends execution of the current process until a child as specified by the pid argument has exited, or until a signal is delivered whose action is to terminate the current process or to call a signal handling function. If a child as requested by pid has already exited by the time of the call (a so-called "zombie" process), the function returns immediately. Any system resources used by the child are freed.

http://linux.about.com/library/cmd/blcmdl2_waitpid.htm

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜