Earlier we introduced what is a zombie process, today we will take a look at how to recycle the PCB left by the process
It’s still the old rules. Check out the video.
Seeking attention
#include<sys/types.h>
Summarize the three functions of this function
- The parent process calls it and blocks and waits for the end of the child process
- Reclaim the remaining resources of the child process
- Get the status of the end of the child process
Take a look at some macros for judging the return status [I translated it into Chinese with Youdao, so that everyone can understand]
1.WIFEXITED (stat_val)
If it returns status for a normally terminated child process, it is calculated as a non-zero value.
2.WEXITSTATUS (stat_val)
If the value of WIFEXITED(stat_val) is non-zero, then this macro will be calculated as the 8-bit low-level value of the status parameter
The value passed by the child process to _exit() or exit(), or the value returned by the child process from main().
3.WIFSIGNALED (stat_val)
If the child process terminated due to receiving a signal returns status, it is calculated as a non-zero value
Not captured (see <signal.h>).
4.WTERMSIG (stat_val)
If the value of wifsignal (stat_val) is non-zero, the macro will calculate the number of signals that cause ter-
The minimum value of the child process.
5.WIFSTOPPED (stat_val)
If the status is returned for the currently stopped child process, it is calculated as a non-zero value.
6.WSTOPSIG (stat_val)
If the value of WIFSTOPPED(stat_val) is non-zero, then this macro will count the number of signals that generate child elements
The process stops.
7.WIFCONTINUED (stat_val)
If the status is returned from the child process continued after the job control is stopped, it is calculated as a non-zero value.
Code Demo
#include <iostream>
#include <unistd.h>
#include <sys/wait.h>
using namespace std;
int
main(int argc, char*argv[])
{
pid_t pid, wpid;
pid = fork();
if(pid == 0){
cout << "hello world!" << endl;
sleep(60);
}else if(pid > 0){
printf("I am parent, ID: %u\n", getpid());
int status;
printf("wait son die....\n");
if((wpid = wait(&status)) == -1){ // block wait son progress die
perror("wait error");
exit(1); // clear the PCB of son
} // get reason about son's die
if(WIFEXITED(status)!=0 && WIFSIGNALED(status)==0){
printf("son progress normal exit\n");
printf("son progress exit status : %d \n", WEXITSTATUS(status));
}else{// 0
printf("son expretion exit,signal ID:%d \n", WTERMSIG(status));
}
printf("I am parent, ID: %u, wait son ID: %u \n", getpid(), wpid);
}else{
perror("fork error");
exit(1);
}
return 0;
}
effect: