Linux waits for process end wait () and Waitpid ()

Source: Internet
Author: User
Tags exit in function prototype printf sleep terminates

If a child process is preceded by a parent process, the wait () function is invoked by the parent process and the wait () function is not invoked to produce two different results:
--> If the parent process does not invoke the wait () and the Waitpid () function, the child process enters a zombie state.
--> If the parent process calls the wait () and the Waitpid () function, it does not make the child process a zombie process.
What is this for? Now we're going to delve into the wait () function and the Waitpid () function.

Wait () and Waitpid () learning

1. First, let's take a look at their function prototypes:
In Terminal input command: Man 2 wait
You'll see its function prototype:

  code is as follows copy code
name
       wait, waitpid, waitid-wait for process to change state
Synopsis
&NBSP;&NBSP ;     #include <sys/types.h>
       #include <sys/ Wait.h>
       pid_t Wait (int *status);
        pid_t waitpid (pid_t pid, int *status, int options);
       int Waitid (idtype_t idtype, id_t ID, siginfo_t *infop, int options);

We can see the addition of the Waitid () function in version 2.6.

2. The function of Wait () and Waitpid ():

The 1> wait () function causes the parent process to suspend execution, until one of its subprocess ends, the return value of the function is the PID of the child process that terminates the run, and the variable that the parameter status points to holds the exit code of the subprocess, that is, the value returned from the main function of the child process or the exit in the subprocess () The parameters of the function. If the status is not a null pointer, the state information is written to the variable it points to.
Note: Once the process has called wait, it immediately blocks itself, and the wait automatically analyzes whether a subprocess of the current process has exited, and if it finds a subprocess that has become a zombie, wait collects the information about the child process and then destroys it and returns If no such child process is found, the wait will always block here until one appears.
Macros in the 2> header file sys/wait.h that define the process exit status.
Let's look at the official explanation first.
a.wifexited (status) Returns True if the child terminated normally, which, by calling exit (3) or _exit (2), or by Retu Rning from Main ().
Translation:
wifexited (status) Jozo returns a value other than 0 when the process ends normally. That is, call exit (3), _exit (3), or the value returned from the main () function.

B. Wexitstatus (status) Returns the exit status of the child. This is consists of the least significant 8 bits of the status argument that the child specified in a call to exit (3) or  _exit (2) or as the argument for a return statement in Main (). This macro should is employed if wifexited returned true.
Translation:
Wexitstatus (status) If the macro wifexied returns a value other than 0, it returns the lower 8 bits in the exit or _exit parameter in the subprocess.

c.wifsignaled (status) Returns True if the child process is terminated by a signal.
Translation:
wifsignaled (status) Jozo process exception termination returns a value other than 0.

D. Wtermsig (status) Returns the number of the signal that caused the child process to terminate. This macro should is employed if wifsignaled returned true.
Translation:
Wtermsig (status) Returns the signal number that causes the child process to terminate abnormally if the return value of the macro wifsignaled is Non-zero.

e.wifstopped (status) Returns True if the child process is stopped by delivery of a signal; This are only possible if the using WUN? Traced or when it is being traced (Ptrace (2)).
Translation:
The wifstopped (status) Jozo process returns a non-0 value because of an unexpected pause. When calling Wun? This is possible when a traced or subprocess is being tracked.

F. Wstopsig (status) Returns the number of the signal which caused to stop. This macro should is employed if wifstopped returned true.
Translation:
Wstopsig (status) Returns a signal number that suspends a child process if the macro wifstopped returns a Non-zero value.

g.wifcontinued (status) (since Linux 2.6.10) returns true if the child process wasresumed by delivery of Sigcont.
Translation:
wifcontinued (status) (after version 2.6) returns a non-0 value if the child process recovers through Sigcont.

3>waitpid () function
(1). Let's take a look at a classic example of a waitpid (): When we downloaded the A software installer, it started another rogue software installer B at the end of the installation, and when the B was installed, it told you that all the installations were complete. A and B are in different processes, a how to start B and know that the B installation is complete? You can simply start B with fork in A and then use Waitpid () to wait for the end of B.
(2). Waitpid () is also used to wait for the end of a child process, but it is used to wait for a particular process to end. Parameter PID indicates the PID of the child process to wait, and the meaning of the parameter status is the same as the status in the Waiting () function. The options parameter can be used to change the behavior of the waitpid, and if you assign the parameter to Wnohang, the parent process is not suspended and immediately returns the code behind the execution.
(3). Value of parameter PID in Waitpid () function
Let's take a look at the official explanation:
The value of PID can be:
<-1 meaning wait for any child process whose process group ID are equal to the absolute value of PID.
-1 meaning wait for any child process.
0 meaning wait for "any" child process whose process group ID are equal to that of the calling process.
> 0 meaning wait for the "child" whose process ID is equal to the value of PID.
translation:
The value of the PID can be in the lower self:
< 1 waits for any child process whose group ID equals the PID absolute value.
=-1 wait for any child process
=0 waits for any process whose group ID equals the group ID of the calling process
> 0 Child processes waiting for their process ID equal to PID exit
(4). An application of the Waitpid () function:
If you want the parent process to periodically check whether a particular child process has exited, you can use the following method:
Waitpid (child_pid, (int *) 0, Wnohang);
It returns 0 if the child process has not exited, and returns CHILD_PID if the child process has ended. Returns-1 if the call fails. The reasons for failure include the absence of the subprocess, the inconsistent parameters, and so on.

3, the difference between wait () and waitpid () function
(1). Before a child process terminates, wait () causes its caller to block, and Waitpid () has an option that causes the caller to not block.
(2). Waitpid () does not wait for the first aborted child process after its invocation, it has several options to control the process it waits for.
(3). for wait (), the only error is that the calling process does not have a subprocess, for Waitpid (), if the specified process or process group does not exist, or the process specified by the parameter PID is not a child of the calling process, it may be wrong.
(4). Waitpid () provides three features that are not available for wait (): one is that waitpid () waits for a particular process, and that Waitpid () provides a non-blocking version of Waiting () (sometimes the state of a child process that you want to take, but does not want the parent process to block. Waitpid () provides one such option: Wnohang, which allows the caller to not block, and the third is waitpid () supports job control.
(5). The function of Wait (&status) equals Waitpid ( -1, &status, 0);

Function instance: The state of a child process that is sometimes desired, but does not want the parent process to block, Waitpid () provides one such option: Wnohang, which allows the caller to not block

  code is as follows copy code

#include <sys/wait.h>
#include <unistd.h>
#include < STDIO.H>

Int main ()
{
 pid_t PR, PC;

 do
 {
  pr = waitpid (PC, NULL, Wnohang);

  if (pr = 0)
  {
   printf ("No child exited\n");
    sleep (1);
  }

 }
 while (pr = 0);

 if (pr = PC)
 {
  printf ("Successfully get child%d\n", PR);
 
 else< br>  {
  printf ("Some error occured\n");
 }

 return 0;
}

 

Summarize
The kernel sends a SIGCHLD signal to its parent process, whether or not the process terminates normally, when the wait or Waitpid function is invoked
(a) If all of the child processes are run, the parent process can be blocked.
(b) If the child process terminates, the wait immediately returns the child process termination status.
(c) If no child processes are running, return the error immediately.

4. Function Realization:
function Instance 1. (see a simple example to see how the process calls the wait () function and how it executes?) )

The code is as follows Copy Code

#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdlib.h>

int main ()
{
pid_t child;
int i;

Child = fork ();

if (Child < 0)
{
printf ("Create failed!\n");
Exit (1);
}
else if (0 = child)
{
printf ("This are the child process pid=%d\n", Getpid ());

for (i = 0; i < 5; i++)
{
printf ("This are the child process print%d!\n", i + 1);
}

printf ("The Child end\n");
}
Else
{
printf ("This is the father process, ppid=%d\n", Getppid ());
printf ("Father wait for the child end\n");
Wait (&child);
printf ("Father end\n");
}
}

The function is compiled:
1
GCC wait.c-o Wait
2
./wait
Function Execution Result:
This is the father process, ppid=3303
Father wait for the child end
This are the child process pid= 3356
This is the child process print 1!
This is the child process print 2!
This is the child process print 3!
This is the child process print 4!
This is the child process print 5!
The child End
Father End

Description
From the above program we can drill down to the execution of the Wait () function:
When the parent process calls the wait () function, it is suspended until the child process ends.

function Instance 2 (now we are going through an instance to get a deeper understanding of the execution of the Wait () function)

The code is as follows Copy Code

#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdlib.h>

int main ()
{
pid_t pid;
Char *msg;
int i;
int Exit_code;

printf ("Tiger Study how to get Exit code\n");
PID = fork ();

if (PID = = 0)/* Child process * *
{
msg = "Child process is running";
i = 5;
Exit_code = 37;
}
else if (PID > 0)/* Parent Process * *
{
Exit_code = 0;
}
Else
{
Perror ("Process creation failed\n");
Exit (1);
}

if (PID > 0)/* Parent Process * *
{
int status;
pid_t Child_pid;
Child_pid = Wait (&status);

printf ("Child process has exited, pid=%d\n", child_pid);
if (wifexited (status))
{
printf ("Child exited with code%d\n", Wexitstatus (status));
}
Else
{
printf ("Child exited abnormally\n");
}
}
else/* Child process * *
{
while (i--> 0)
{
Puts (msg);
Sleep (1);
}
}

}

After the function has been compiled:

$ gcc Wait1.c-o wait1

$./wait1

Function Execution Results:
Tiger Study how-Get exit code
 child process is running
 child process is running
 child process is running
 child process was running
 child process is running
child process ha s exited,pid = 3816
Child exited with code 0
 
Description:
The parent process calls the wait () function and is suspended (we can open another terminal, enter the command: PS aux, you can see the parent process The row result is s) until the child process ends. After the child process finishes, the wait () function returns the PID of the child process that just ended, and the macro wexitstatus gets the exit code for the subprocess.
 
 
Note
If the process that calls wait () has no aborted subprocess, but one or more child processes are still running, wait will block until the first termination of the existing child process. The
Waitpid function waits for which process and whether it is blocked gives us more control. First, the PID parameter allows us to specify the process ID to wait for, and a value of 1 indicates the child process waiting for the first aborted. Second, the options parameter allows us to specify additional options. The most common option is Wnohang, which tells the kernel not to block if no child process has been terminated.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.