This article will record the process of learning the fork and wait (waitpid) functions.
1. Fork
In Linux, the fork function is often used to create a new process. It is very special. When executed once, two values are returned, which is very different from the general function, this has aroused my high attention.
Prototype: pid_t fork (void)
Return: 0 -- sub-process
> 0 (child process ID) -- parent process
-1 -- Error
Next, we will continue to introduce the wait function, and finally provide routine practices.
2. Wait
The wait function is used to block the parent process until a child process ends or the process receives a specified signal. If the parent process has no child process or the child process has ended, wait will return immediately.
Prototype: pid_t wait (int * Status)
Parameter: Status indicates the status when the sub-process exits. If it is null, the sub-process ends in any State. If this parameter is not set, the child process is terminated in the specified state.
Return: subprocess id -- Success
-1 -- Failure
Examples of fork and wait usage are as follows:
# Include <sys/types. h> <br/> # include <sys/Wait. h> <br/> # include <unistd. h> <br/> # include <stdlib. h> </P> <p> int main (void) <br/> {<br/> pid_t PC, PR; </P> <p> Pc = fork (); <br/> If (0 = pc) // enter the sub-process <br/>{< br/> printf ("I'm child process with PID of % d/N", getpid ()); <br/> sleep (10); // sleep for 10 S <br/>}< br/> else if (Pc> 0) // enter the parent process <br/>{< br/> Pr = wait (null); // wait until the child process ends, obtain the sub-process id <br/> printf ("I catch child process with PID of % d/N", Pr ); <br/>}</P> <p> return 0; <br/>}
Program explanation: Pc = fork (); this statement creates a new sub-process and determines whether the parent process or sub-process will be executed based on the returned value. Fork () and vfork () is not the same, after creating a sub-process, then call the parent process or sub-process is random, specific about fork and vfork Introduction Please refer to the http://blog.csdn.net/jarvis_xian/archive/2011/05/11/6412658.aspx
Since the execution of the parent process or child process is random, the preceding routine is described in two cases.
1. Execute the sub-process first
The program runs from top to bottom. After the sub-process prints the statement, sleep for 10 s, the parent process takes over, waits until the sub-process ends (sleep ends when the sub-process ends), and obtains the PID of the sub-process, then print it out.
2. Execute the parent process first.
The parent process executes the wait function at the beginning. Because the child process has not ended (or even not started, but already exists), the parent process is in a blocked state, now that the parent process is blocked, you can turn to execute the child process. The next process is the same as the first case.
You can try to compile and run the above program to see the effect. This shows the effect of fork and wait at a glance.