wait() - Unix, Linux System Call

Unix - Home
Unix - Getting Started
Unix - File Management
Unix - Directories
Unix - File Permission
Unix - Environment
Unix - Basic Utilities
Unix - Pipes & Filters
Unix - Processes
Unix - Communication
Unix - The vi Editor
Unix - What is Shell?
Unix - Using Variables
Unix - Special Variables
Unix - Using Arrays
Unix - Basic Operators
Unix - Decision Making
Unix - Shell Loops
Unix - Loop Control
Unix - Shell Substitutions
Unix - Quoting Mechanisms
Unix - IO Redirections
Unix - Shell Functions
Unix - Manpage Help
Unix - Regular Expressions
Unix - File System Basics
Unix - User Administration
Unix - System Performance
Unix - System Logging
Unix - Signals and Traps
Unix - Useful Commands
Unix - Quick Guide
Unix - Builtin Functions
Unix - System Calls
Unix - Commands List
Unix Useful Resources
Computer Glossary
Who is Who
Copyright © 2014 by tutorialspoint
wait, waitpid - wait for process to change state
#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 );


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 );

All of these system calls are used to wait for state changes
in a child of the calling process, and obtain information
about the child whose state has changed.
A state change is considered to be: the child terminated;
the child was stopped by a signal; or the child was resumed by a signal.
In the case of a terminated child, performing a wait allows
the system to release the resources associated with the child;
if a wait is not performed, then terminated the child remains in
a "zombie" state (see NOTES below).
If a child has already changed state, then these calls return immediately.
Otherwise they block until either a child changes state or
a signal handler interrupts the call (assuming that system calls
are not automatically restarted using the SA_RESTART flag of
sigaction(2)). In the remainder of this page, a child whose state has changed
and which has not yet been waited upon by one of these system
calls is termed
waitable.
The wait() system call suspends execution of the current process until one of its children terminates.
The call wait(&status) is equivalent to:
    waitpid(-1, &status, 0);

The waitpid() system call suspends execution of the current process until a
child specified by pid argument has changed state.
By default,
waitpid() waits only for terminated children, but this behaviour is modifiable
via the
options argument, as described below.
The value of  pid can be:
The value of options is an OR of zero or more of the following constants:
(For Linux-only options, see below.) The
WUNTRACED and WCONTINUED options are only effective if the
SA_NOCLDSTOP flag has not been set for the
SIGCHLD signal (see sigaction(2)).
If status is not NULL, wait() and waitpid() store status information in the int to which it points.
This integer can be inspected with the following macros (which
take the integer itself as an argument, not a pointer to it, as is done in wait() and waitpid()!): 
The waitid() system call (available since Linux 2.6.9) provides more precise
control over which child state changes to wait for.
The
idtype and
id arguments select the child(ren) to wait for, as follows:
If WNOHANG was specified in
options and there were no children in a waitable state, then
waitid() returns 0 immediately and
the state of the
siginfo_t structure pointed to by
infop is unspecified.
To distinguish this case from that where a child was in a
waitable state, zero out the
si_pid field before the call and check for a non-zero value in this field
after the call returns.
wait(): on success, returns the process ID of the terminated child;
on error, -1 is returned.
waitpid(): on success, returns the process ID of the child whose state has changed;
on error, -1 is returned; if WNOHANG was specified and no child(ren) specified by pid has yet changed state, then 0 is returned.
waitid(): returns 0 on success or
if
WNOHANG was specified and no child(ren) specified by
id has yet changed state;
on error, -1 is returned.
Each of these calls sets
errno to an appropriate value in the case of an error.
A child that terminates, but has not been waited for becomes a "zombie".
The kernel maintains a minimal set of information about the zombie
process (PID, termination status, resource usage information)
in order to allow the parent to later perform a wait to obtain
information about the child.
As long as a zombie is not removed from the system via a wait,
it will consume a slot in the kernel process table, and if
this table fills, it will not be possible to create further processes.
If a parent process terminates, then its "zombie" children (if any)
are adopted by init(8),
which automatically performs a wait to remove the zombies.
POSIX.1-2001 specifies that if the disposition of
SIGCHLD is set to
SIG_IGN or the
SA_NOCLDWAIT flag is set for
SIGCHLD (see
sigaction(2)),
then children that terminate do not become zombies and a call to
wait() or
waitpid() will block until all children have terminated, and then fail with
errno set to
ECHILD. (The original POSIX standard left the behaviour of setting
SIGCHLD to
SIG_IGN unspecified.)
Linux 2.6 conforms to this specification.
However, Linux 2.4 (and earlier) does not: if a
wait() or
waitpid() call is made while
SIGCHLD is being ignored, the call behaves just as though
SIGCHLD were not being ignored, that is, the call blocks until the next child
terminates and then returns the process ID and status of that child.
In the Linux kernel, a kernel-scheduled thread is not a distinct
construct from a process. Instead, a thread is simply a process
that is created using the Linux-unique
clone(2)
system call; other routines such as the portable
pthread_create(3)
call are implemented using
clone(2).

Before Linux 2.4, a thread was just a special case of a process,
and as a consequence one thread could not wait on the children
of another thread, even when the latter belongs to the same thread group.
However, POSIX prescribes such functionality, and since Linux 2.4
a thread can, and by default will, wait on children of other threads
in the same thread group.
The following Linux-specific
options are for use with children created using
clone(2);
they cannot be used with
waitid():
The following program demonstrates the use of fork(2) 
and
waitpid(2).
The program creates a child process.
If no command-line argument is supplied to the program,
then the child suspends its execution using
pause(2),
to allow the user to send signals to the child.
Otherwise, if a command-line argument is supplied,
then the child exits immediately,
using the integer supplied on the command line as the exit status.
The parent process executes a loop that monitors the child using
waitpid(2),
and uses the W*() macros described above to analyse the wait status value.
The following shell session demonstrates the use of the program:

$ ./a.out &
Child PID is 32360
[1] 32359
$ kill -STOP 32360
stopped by signal 19
$ kill -CONT 32360
continued
$ kill -TERM 32360
killed by signal 15
[1]+  Done                    ./a.out
$


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

int
main(int argc, char *argv[])
{
    pid_t cpid, w;
    int status;

    cpid = fork();
    if (cpid == -1) { perror("fork"); exit(EXIT_FAILURE); }

    if (cpid == 0) {            /* Code executed by child */
        printf("Child PID is %ld\n", (long) getpid());
        if (argc == 1)
            pause();                    /* Wait for signals */
        _exit(atoi(argv[1]));

    } else {                    /* Code executed by parent */
        do {
            w = waitpid(cpid, &status, WUNTRACED | WCONTINUED);
            if (w == -1) { perror("waitpid"); exit(EXIT_FAILURE); }

            if (WIFEXITED(status)) {
                printf("exited, status=%d\n", WEXITSTATUS(status));
            } else if (WIFSIGNALED(status)) {
                printf("killed by signal %d\n", WTERMSIG(status));
            } else if (WIFSTOPPED(status)) {
                printf("stopped by signal %d\n", WSTOPSIG(status));
            } else if (WIFCONTINUED(status)) {
                printf("continued\n");
            }
        } while (!WIFEXITED(status) && !WIFSIGNALED(status));
        exit(EXIT_SUCCESS);
    }
}


$ ./a.out &
Child PID is 32360
[1] 32359
$ kill -STOP 32360
stopped by signal 19
$ kill -CONT 32360
continued
$ kill -TERM 32360
killed by signal 15
[1]+  Done                    ./a.out
$




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


int
main(int argc, char *argv[])
{
    pid_t cpid, w;
    int status;


    cpid = fork();
    if (cpid == -1) { perror("fork"); exit(EXIT_FAILURE); }


    if (cpid == 0) {            /* Code executed by child */
        printf("Child PID is %ld\n", (long) getpid());
        if (argc == 1)
            pause();                    /* Wait for signals */
        _exit(atoi(argv[1]));


    } else {                    /* Code executed by parent */
        do {
            w = waitpid(cpid, &status, WUNTRACED | WCONTINUED);
            if (w == -1) { perror("waitpid"); exit(EXIT_FAILURE); }


            if (WIFEXITED(status)) {
                printf("exited, status=%d\n", WEXITSTATUS(status));
            } else if (WIFSIGNALED(status)) {
                printf("killed by signal %d\n", WTERMSIG(status));
            } else if (WIFSTOPPED(status)) {
                printf("stopped by signal %d\n", WSTOPSIG(status));
            } else if (WIFCONTINUED(status)) {
                printf("continued\n");
            }
        } while (!WIFEXITED(status) && !WIFSIGNALED(status));
        exit(EXIT_SUCCESS);
    }
}

SVr4, 4.3BSD, POSIX.1-2001.