Linux 下子進程與父進程的關系


我們知道,Linux下父進程可以使用fork 函數創建子進程,但是當父進程先退出后,子進程會不會也退出呢?

通過下面這個小實驗,我們能夠很好的看出來:

/********  basic.c ********/
1
#include "basic.h"

2 3 pid_t Fork(void) 4 { 5 pid_t pid = fork(); 6 if (pid < 0) { 7 fprintf(stderr, "Fork error: %s\n", strerror(errno)); 8 exit(0); 9 } 10 11 return pid; 12 }
 1 **********  basic.h  ***********
 2 
 3 #ifndef __CSAPP_BASIC_H
 4 #define __CSAPP_BASIC_H
 5 
 6 #include <stdio.h>
 7 #include <errno.h>
 8 #include <stdlib.h>
 9 #include <signal.h>
10 #include <unistd.h>
11 #include <string.h>
12 /* function definition concerned with basic.c */
13 pid_t Fork();
14 
15 #endif
 1 *******  fork.c  *********
 2 
 3 #include "basic.h"
 4 
 5 int main()
 6 {
 7     int pid = Fork();
 8     int x = 2;
 9 
10     if (pid == 0) {
11         printf("child: pid = %d, ppid = %d, x = %d\n", getpid(), getppid(), ++x);
12         sleep(3);
13         
14         printf("child: pid = %d, ppid = %d, x = %d\n", getpid(), getppid(), ++x);
15         exit(0);
16     }
17 
18     printf("parent: pid = %d, ppid = %d, x = %d\n", getpid(), getppid(), --x);
19 
20 }

通過 gcc fork.c basic.c -o fork 編譯即可的 fork 程序。 運行 ./fork
可以看出父進程首先退出,退出前child的PPID為12256, 退出后子進程的PPID變為了 1.說明父進程退出后的子進程由 init 超級進程1領養。而該進程是不絕不會退出的。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM