进程的创建和回收

进程的创建和回收

fork:创建子进程

  • fork()会返回两次,在子进程中返回 0, 在父进程中返回子进程的 pid,返回 -1 表示创建失败
  • 创建成功之后,子进程和父进程共享数据(只有pcb中的一些数据不同,如 pid,ppid)。读时共享,写时复制。

孤儿进程 VS 僵尸进程

  • 孤儿进程:父进程结束,子进程运行 --------> 子进程的父进程设置为 init (pid = 1) ---------------> 子进程结束时init 回收
  • 僵尸进程:子进程结束,父进程运行 ---------> 父进程未结束且未回收子进程(wait)---------------> 僵尸进程

子进程回收

  • wait:等待任意一个子进程结束,并回收。阻塞等待
  • waitpid:指定一个子进程等待结束并回收,可以设置阻塞和非阻塞
/*********************************************************
Copyright © 2022 Shengkai Liu. All rights reserved.
FileName:   wait.c
Author:     Shengkai Liu
Date:       2022-05-31
***********************************************************/

#include <unistd.h>         // fork, getpid
#include <stdio.h>          // printf, perror
#include <wait.h>           // wait
#include <stdlib.h>         // exit

int main()
{
    // create a sub-process
    pid_t pid = fork();
    
    // prints its own pid if the sub-process
    if (pid == 0)
    {
        printf("pid of the child process: %d\n", getpid());
        exit(0);
    }


    // Recycle sub-process resources by wait
    int status;
    pid = wait(&status);
    if (pid == -1) perror("wait");

    printf("pid of recycled sub-processes: %d\n", pid);

    return 0;
}
/*********************************************************
Copyright © 2022 Shengkai Liu. All rights reserved.
FileName:   waitpid.c
Author:     Shengkai Liu
Date:       2022-05-31
***********************************************************/

#include <unistd.h>         // fork, getpid
#include <stdio.h>          // printf, perror
#include <wait.h>           // waitpid
#include <stdlib.h>         // exit

int main()
{
    // create a sub-process
    pid_t pid = fork();
    
    
    if (pid == 0)
    {
        // prints its own pid if the sub-process
        printf("pid of the child process: %d\n", getpid());
        exit(0);
    }
    else if (pid > 0)
    {
        // Recycle sub-process resources by wait
        int status;
        pid = waitpid(pid, &status, 0);
        if (pid == -1) perror("wait");

        printf("pid of recycled sub-processes: %d\n", pid);
        exit(0);
    }
    return -1;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值