分享

Linux提高:孤儿进程

 流楚丶格念 2022-01-14

文章目录

题目

编程实现孤儿进程

知识回顾

孤儿进程概念

孤儿进程:一个父进程退出,而它的一个或多个子进程还在运行,那么那些子进程将成为孤儿进程。孤儿进程将被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;
}

    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多