環境:Vmware Workstation;CentOS-6.4-x86_64
說明:
通過給程序發送信号,也可以回收已經消亡的子程序:signal(SIGCHLD, SIG_IGN);
程式如下:
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
int main(int argc, char *args[])
{
// 執行fork并擷取傳回值
pid_t id = fork();
// 判斷fork是否成功
// 當傳回值為-1時,說明fork失敗
if (id == -1)
{
printf("fork failed : %s", strerror(errno));
}
if (id > 0)
{
// 通過信号回收已經死亡的子程序
signal(SIGCHLD, SIG_IGN);
// 父程序休眠20秒
sleep(20);
}
else
{
// 子程序立即退出
exit(0);
}
return 0;
}
編譯并執行程式:
[[email protected] mycode]$ gcc -o main main.c
[[email protected] mycode]$ main
程式還沒有退出的時候打開另一個終端。
打開另一個終端檢視程序資訊:
[[email protected] ~]$ ps -aux
negivup 15271 0.0 0.0 3916 340 pts/1 S+ 18:33 0:00 main
negivup 15273 2.0 0.0 110236 1144 pts/0 R+ 18:33 0:00 ps -aux
發現沒有已經死亡但沒被回收的子程序。
PS:根據傳智播客視訊學習整理得出。