Linux系统编程进程6-退出以及退出状态收集

正常退出
1.main函数调用return
2.进程调用exit(),标准c库
3.进程调用_exit()或者_Exit,属于系统调用
补充
1.进程最后一个线程返回
2.最后一个线程调用pthread_exit
异常退出
1.调用abort
2.当进程收到某些信号时,如crtl+c
3.最后一个线程对取消(cancellation)请求做出响应

在任一情况下,该终止进程的父进程都能用wait或waitpid函数取得其终止状态

父进程等待子进程退出并且收集子进程的退出状态,子进程退出状态不被收集,变成僵尸进程(僵死进程)

#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdlib.h>
int main()
{
        pid_t pid;
        int cnt = 0;
        int status = 10;

        pid = fork();

        if(pid>0){

                wait(&status);	// wait阻塞,等待收集子进程资源,所以先执行子进程------敲重点
                //waitpid(pid,&stats,WNOHANG);	//挂起状态,子父一起运行,不阻塞,会出现僵尸进程
                printf("child quit,child status = %d\n",WEXITSTATUS(status));	//需要用宏解析status
                while(1){
                        printf("cnt = %d\n",cnt);
                        printf("this is father print,pid = %d\n",getpid());
                        sleep(1);
                }


        }
        else if(pid == 0){
                while(1){
                        printf("this is chilid print,pid = %d\n",getpid());
                        sleep(1);
                        cnt++;
                        if(cnt == 5){
                                exit(3);
                        }
                }
        }
        return 0;
}

孤儿进程:父进程如果不等待子进程退出,在子进程结束之前就结束了自己的“生命”,此时子进程叫做孤儿进程
Linux避免系统存在过多孤儿进程,init进程收留孤儿进程,变成孤儿进程的父进程。

#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdlib.h>
//孤儿进程
int main()
{
        pid_t pid;
        int cnt = 0;
        int status = 10;

        pid = fork();

        if(pid>0){

                printf("this is father print,pid = %d\n",getpid());
        }

        else if(pid == 0){
                while(1){
                        printf("this is chilid print,pid = %d,my father pid = %d\n",getpid(),getppid());
                        sleep(1);
                        cnt++;
                        if(cnt == 5){
                                exit(3);
                        }
                }
        }
        return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

sunshime.

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

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

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

打赏作者

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

抵扣说明:

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

余额充值