孤兒進程介紹
父進程先於子進程結束,則子進程成為孤兒進程,子進程的父進程成為init進程,稱為init進程領養孤兒進程。孤兒進程就是父進程先死亡,子進程成為孤兒進了孤兒院了。 孤兒進程類比 代碼展示
#include <stdio.h>#include <stdlib.h>#include <string.h>#include <unistd.h>#include <fcntl.h>#include <error.h>#include <sys/errno.h>void perr(const char* str){ perror(str); exit(1);}//驗證孤兒進程int main(int argc,char* argv[]){ pid_t pid; if( (pid = fork()) == 0 ) //子進程 { printf("i am child process,pid = %d,ppid = %d,i sleep 5s.\n",getpid(),getppid()); sleep(5); printf("now,i am orphan process,pid %d,ppid = %d.\n",getpid(),getppid()); exit(0); }else if( pid > 0 ) //父進程 { printf("i am parent process,pid = %d,ppid = %d.\n",getpid(),getppid()); sleep(1); printf("parent process exit\n"); }else if( pid < 0 ) { perr("fork error"); } return 0;}
運行效果
孤兒進程分析
從代碼運行效果可以看出父進程先死亡,子進程成為孤兒進程後,父進程變為pid = 1的init進程。由於父進程的父進程是bash進程,父進程執行完畢,回到bash調用回到控制台終端,此時孤兒進程還活著,5秒後要進行列印操作所以將輸出列印到螢幕,所以bash的游標沒有在$的後面。