;process will get when its parent dies. This value is cleared for the child of a fork(2) and (since Linux 2.4.36 / 2.6.23) when executing a set-user-ID or set-group-ID binary, or a binary that has associated capa‐ bilities (see capabilities(7)). This value is preserved across execve(2).
内容很多,主要意思为:设置一个信号,当父进程退出的时候,子进程将会收到该信号。
那么根据这个,我们完全可以在父进程退出时,也给子进程一个退出的信号。程序代码如下:
#include <stdio.h> #include <stdlib.h> #include <errno.h> #include <unistd.h> #include <sys/prctl.h> #include <signal.h> int main(void) { pid_t pid;
运行结果:
parent process. child process. child pid:17625,parent pid:17624 sleep 10 seconds.
可以看到,由于加入了
prctl(PR_SET_PDEATHSIG,SIGKILL);
在父进程退出时,子进程将会收到SIGKILL信号,而进程收到该信号的默认动作则是退出。因而最后不会看到它成为孤儿进程,被其他进程所收养。需要注意的是,该函数并非所有系统都支持。
总结
有些情况下,我们常常需要父子进程共存亡,子进程退出时,父进程可以通过wait捕捉子进程的退出状态,但是父进程退出时,子进程却难以得知。因此,在最初fork子进程的时候,便表明了,当父进程退出的时候,子进程收到SIGKILL信号,最终也退出。以此达到同生共死的目的。当然也可以发送其他信号,由子进程捕获该信号并做后续处理。
练习
尝试将上面的代码在非图形界面的linux操作系统中运行,看看 |