简体   繁体   中英

Can a child process wait for the parent process to terminate in Linux programming in C?

在Linux的C编程中,我知道wait()函数用于等待子进程终止,但是子进程是否有一些方法(或函数)可以等待父进程终止?

Linux has an extension (as in, non-POSIX functions) for this. Look up prctl ("process-related control").

With prctl , you can arrange for the child to get a signal when the parent dies. Look for the PR_SET_PDEATHSIG operation code used with prctl .

For instance, if you set it to the SIGKILL signal, it effectively gives us a way to have the children die when a parent dies. But of course, the signal can be something that the child can catch.

prctl can do all kinds of other things. It's like an ioctl whose target is the process itself: a "process ioctl".

Short answer: no.

A parent process can control the terminal or process group of its children, which is why we have the wait() and waitpid() functions. A child doesn't have that kind of control over its parent, so there's nothing built in for that.

If you really need a child to know when its parent exits, you can have the parent send a signal to the child in an atexit() handler, and have the child catch that signal.

In Linux, you can use prctl with the value PR_SET_PDEATHSIG to establish a signal that will be sent to your process when the thread that created it dies. Maybe you find it useful.

当父进程结束时,子进程被init采用,因此如果ppid()==1或ppid()!=就足以检查子进程,而不是原始的PPID,这意味着父进程已完成。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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