打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
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;
}

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
孤儿进程与僵尸进程[总结]
linux中创建多个子进程的方法
Linux进程间通信示例(多通道)
Linux--进程组、会话、守护进程
多进程编程小例子(YC)
socketpair理解
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服