Linux提高:孤儿进程

题目

编程实现孤儿进程

知识回顾

孤儿进程概念

孤儿进程:一个父进程退出,而它的一个或多个子进程还在运行,那么那些子进程将成为孤儿进程。孤儿进程将被init进程(进程号为1)所收养,并由init进程对它们完成状态收集工作。

代码

实现孤儿进程,需要父进程先于子进程结束,故只需要在子进程中只需要 sleep(5)即可,同时为了观察现象,可以让 sleep 时间长一点

异步操作

运行结果如下图:
在这里插入图片描述

/*************************************************************************
    > File Name: main.c
    > Author: 杨永利
    > Mail: 1795018360@qq.com 
    > Created Time: 2021年07月16日 星期五 17时42分46秒
 ************************************************************************/

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char const *argv[])
{
	pid_t pid;
	pid = fork();
	if (pid < 0) {
		// fork 出错,创建子进程失败
		perror("fork error:");
		exit(1);
	}
	else if (pid == 0) {
		// 子进程
		printf("I am the child process.\n");
		//输出进程 ID 和父进程 ID
		printf("pid: %d\tppid:%d\n", getpid(), getppid());
		printf("I will sleep five seconds.\n");
		//睡眠 5s,保证父进程先退出
		sleep(5);
		printf("pid: %d\tppid:%d\n", getpid(), getppid());
		printf("child process is exited.\n");
	}
	else {
		// 父进程
		printf("I am father process.\n");
		//父进程睡眠 1s,保证子进程输出进程 id
		sleep(1);
		printf("father process is exited.\n");
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

呆萌宝儿姐

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值