pid = fork()之後,如pid為0,是child的執行程式段, child程式段,註冊了一個alarm signal,callback function為killchild(), 這邊調用alarm(3),即三秒後會發出alarm signal到這個程序, 再調用kill()砍掉目前的process,即child process。
#include <stdio.h> #include <signal.h> void killchild(int signum) { printf("kill id = %d\n", getpid()); kill(getpid(), SIGKILL); } int main() { pid_t pid; pid = fork(); if(pid == 0) { printf("child id = %d\n", getpid()); signal(SIGALRM, killchild); alarm(3); while(1); } else if(pid < 0){ printf(" we have an error\n"); } else { printf("parent id = %d\n", getpid()); while(1); } }
程序運行後,先打印parent process ID和child process ID, 三秒之後,再kill child process。
pi@raspberrypi:~/Work $ gcc test.c -o test && ./test parent id = 1750 child id = 1751 kill id = 1751
程序運行後,調用ps來看這個程序創建的兩個process, 1750為parent process,1751為child process, 在三秒後,即alarm signal發出後,可以看到child process狀態變為defunct 狀態defunct,即為zombie process,表示child process已被砍掉, 但由於parent process還在運行,所以child process資源還無法完全釋放, 此child process就變成zombie process。
pi@raspberrypi:~ $ ps -aux | grep test pi 1750 52.5 0.0 1680 356 pts/0 R+ 00:08 0:01 ./test pi 1751 53.0 0.0 1680 84 pts/0 R+ 00:08 0:01 ./test pi 1753 0.0 0.2 4276 1908 pts/1 S+ 00:08 0:00 grep --color=auto test pi@raspberrypi:~ $ pi@raspberrypi:~ $ pi@raspberrypi:~ $ pi@raspberrypi:~ $ pi@raspberrypi:~ $ ps -aux | grep test pi 1750 92.6 0.0 1680 356 pts/0 R+ 00:08 0:04 ./test pi 1751 59.8 0.0 0 0 pts/0 Z+ 00:08 0:02 [test]參考來源pi 1755 0.0 0.2 4276 2004 pts/1 S+ 00:09 0:00 grep --color=auto test
https://stackoverflow.com/questions/35898631/child-process-kill-itself-after-3-seconds-in-fork
沒有留言:
張貼留言