[Programming] C language Linux system programming-waiting for termination of sub-processes (zombie processes), linux stiff
1. subprocesses awaiting termination (zombie processes ):
If a child process ends before the parent process, the kernel sets the child process to a special State. A process in this state is called a zombie process.
After the parent process obtains information about the child process, the child process disappears.
Pid_t wait (int * status );
The parent process will be blocked when calling this method. If the child process is terminated, this method will be called and the pid of the child process will be returned.
# Include <stdio. h> # include <unistd. h> # include <sys/wait. h> int main () {int pid, ppid; int ret = fork (); if (ret> 0) {pid = getpid (); ppid = getppid (); printf ("I am a parent process, pid = % d, ppid = % d, new child process pid = % d \ n", pid, ppid, ret ); int status; int sonPid = wait (& status); printf ("My sub-process, pid = % d, ended \ n", sonPid );} else if (ret = 0) {sleep (2); pid = getpid (); ppid = getppid (); printf ("I Am a sub-process, pid = % d, ppid = % d \ n ", pid, ppid);} else if (ret =-1) {perror (" fork ");}}
Output:
I am a parent process, pid = 22315, ppid = 12479, and the new sub-process pid = 22316
I am a sub-process, pid = 22316, ppid = 22315
My sub-process, pid = 22316, ended
2. if the parent process stops before the child process, the system sets the child process to the init process (pid is 1), and the init process periodically waits for all child processes, make sure there are no dead processes for a long time