进程的创建和回收
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;
}