Linux 下子进程与父进程的关系

本文通过一个小实验解答了Linux环境下父进程先退出时,子进程是否会随之退出的问题。实验证明,子进程会被init超级进程领养,从而避免孤儿进程的出现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我们知道,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领养。而该进程是不绝不会退出的。

转载于:https://www.cnblogs.com/chenchenluo/p/3287438.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值