父程序退出之後,子程序會發生什麼?
阿新 • • 發佈:2018-12-13
在linux中,所有程序都有一個共同的父程序systemd,如果父程序退出了,子程序還沒執行結束,子程序會被stsremd收養
下面用一個小程式來驗證一下:
#include <cstdio> #include <sys/types.h> #include <unistd.h> #include <errno.h> #include <string.h> int func(int x); int main() { pid_t pid; pid=fork(); switch(pid) { case -1: printf("fork failed.%d:%s\n",errno,strerror(errno)); break; case 0: printf("this is child process...\n"); func(pid); break; default: printf("this is parent process...\n"); func(pid); break; } return 0; } int func(int x) { if(x==0) { for(int a=0;a<60;++a) { printf("child:a=%02d\n",a); sleep(1); } } else { for(int a=0;a<30;++a) { printf("parent:a=%02d\n",a); sleep(1); } } return 0; }
在上面的程式中,30秒之後父程序退出,而子程序要60秒才能執行結束,看看會發生什麼
編譯:g++ fork.cpp -o fk
執行:./fk
通過程序樹pstree看看現象:
1、主程序還沒退出
2、主程序退出之後