[Linux] Simulate process waiting (avoid zombie processes)

Zombie processes will greatly accelerate the leakage of our resources, which is very bad, so there are a series of solutions.

Link: Zombie process .

Under normal circumstances, we use two provided library functions to achieve process waiting.

wait function

pid_t wait (int* status);

Detailed interpretation:

1. .pid_t is a signed integer, used to record the pid of the process. The return value of the function has three types: 1. (minus 1)-1->operation error. 2.0->No child process exits. 3. Return the pid of the exited child process.

2. Status is an output parameter, given by the operating system, to record the status information of the exit of the child process. When this parameter is NULL, it means that the parent process does not care about the exit status of the child process.

waitpid function

pid_t waitpid(pid_t pid,int *status,int options);

Interpretation:

1. The return value is the same as wait.

2.The first parameter is used to specify the pid of the child process. If it is -1, it means any child process exits.

3. The output parameter has the same function as wait.

4.
options =0: blocking waiting options=WNOHANG: non-blocking state
Note: Only non-blocking state status can return 0
; (The blocking state will always wait for the exit of the child process, even if it does not, it will wait)

The simulation implementation process waits:

Use waitpid to achieve:
waitpid(-1,&status,0)==wait(&status)
These two ways of writing are equivalent
Insert picture description here
Program running results:

Insert picture description here

Guess you like

Origin blog.csdn.net/zhaocx111222333/article/details/115026426