wait

title: wait(2)

summary: wait for process to change state

text:
# wait(2)

## NAME
wait, waitpid, waitid - wait for process to change state

## SYNOPSIS

```
#include <sys/wait.h>
```

```
pid_t wait(int *wstatus);
pid_t waitpid(pid_t pid, int *wstatus, int options);
```

```
int waitid(idtype_t idtype, id_t id, siginfo_t *infop, int options);

                /* This is the glibc and POSIX interface; see

                   NOTES for information on the raw system call. */
```

Feature Test Macro Requirements for glibc (see feature_test_macros(7)):

waitid():

```
    Since glibc 2.26:

        _XOPEN_SOURCE >= 500 || _POSIX_C_SOURCE >= 200809L

    Glibc 2.25 and earlier:

        _XOPEN_SOURCE

            || /* Since glibc 2.12: */ _POSIX_C_SOURCE >= 200809L

            || /* Glibc <= 2.19: */ _BSD_SOURCE
```

## DESCRIPTION
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 the terminated 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.

### wait() and waitpid()
The wait() system call suspends execution of the calling thread until one of its children terminates. The call wait(&wstatus) is equivalent to:

```
waitpid(-1, &wstatus, 0);
```

The waitpid() system call suspends execution of the calling thread until a child specified by pid argument has changed state. By default, waitpid() waits only for terminated children, but this behavior is modifiable via the options argument, as described below.

The value of pid can be:

< -1

meaning wait for any child process whose process group ID is 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 is equal to that of the calling process at the time of the call to waitpid().

> 0

meaning wait for the child whose process ID is equal to the value of pid.

The value of options is an OR of zero or more of the following constants:

WNOHANG

return immediately if no child has exited.

WUNTRACED

also return if a child has stopped (but not traced via ptrace(2)). Status for traced children which have stopped is provided even if this option is not specified.

WCONTINUED (since Linux 2.6.10)

also return if a stopped child has been resumed by delivery of SIGCONT.

(For Linux-only options, see below.)

If wstatus 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()!):

WIFEXITED(wstatus)

returns true if the child terminated normally, that is, by calling exit(3) or _exit(2), or by returning from main().

WEXITSTATUS(wstatus)

returns the exit status of the child. This 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 be employed only if WIFEXITED returned true.

WIFSIGNALED(wstatus)

returns true if the child process was terminated by a signal.

WTERMSIG(wstatus)

returns the number of the signal that caused the child process to terminate. This macro should be employed only if WIFSIGNALED returned true.

WCOREDUMP(wstatus)

returns true if the child produced a core dump (see core(5)). This macro should be employed only if WIFSIGNALED returned true.

This macro is not specified in POSIX.1-2001 and is not available on some UNIX implementations (e.g., AIX, SunOS). Therefore, enclose its use inside #ifdef WCOREDUMP ... #endif.

WIFSTOPPED(wstatus)

returns true if the child process was stopped by delivery of a signal; this is possible only if the call was done using WUNTRACED or when the child is being traced (see ptrace(2)).

WSTOPSIG(wstatus)

returns the number of the signal which caused the child to stop. This macro should be employed only if WIFSTOPPED returned true.

WIFCONTINUED(wstatus)

(since Linux 2.6.10) returns true if the child process was resumed by delivery of SIGCONT.

### waitid()
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:

idtype == P_PID

Wait for the child whose process ID matches id.

idtype == P_PIDFD (since Linux 5.4)

Wait for the child referred to by the PID file descriptor specified in id. (See pidfd_open(2) for further information on PID file descriptors.)

idtype == P_PGID

Wait for any child whose process group ID matches id. Since Linux 5.4, if id is zero, then wait for any child that is in the same process group as the caller's process group at the time of the call.

idtype == P_ALL

Wait for any child; id is ignored.

The child state changes to wait for are specified by ORing one or more of the following flags in options:

WEXITED

Wait for children that have terminated.

WSTOPPED

Wait for children that have been stopped by delivery of a signal.

WCONTINUED

Wait for (previously stopped) children that have been resumed by delivery of SIGCONT.

The following flags may additionally be ORed in options:

WNOHANG

As for waitpid().

WNOWAIT

Leave the child in a waitable state; a later wait call can be used to again retrieve the child status information.

Upon successful return, waitid() fills in the following fields of the siginfo_t structure pointed to by infop:

si_pid

The process ID of the child.

si_uid

The real user ID of the child. (This field is not set on most other implementations.)

si_signo

Always set to SIGCHLD.

si_status

Either the exit status of the child, as given to _exit(2) (or exit(3)), or the signal that caused the child to terminate, stop, or continue. The si_code field can be used to determine how to interpret this field.

si_code

Set to one of: CLD_EXITED (child called _exit(2)); CLD_KILLED (child killed by signal); CLD_DUMPED (child killed by signal, and dumped core); CLD_STOPPED (child stopped by signal); CLD_TRAPPED (traced child has trapped); or CLD_CONTINUED (child continued by SIGCONT).

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 depends on the implementation. To (portably) 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 nonzero value in this field after the call returns.

POSIX.1-2008 Technical Corrigendum 1 (2013) adds the requirement that when WNOHANG is specified in options and there were no children in a waitable state, then waitid() should zero out the si_pid and si_signo fields of the structure. On Linux and other implementations that adhere to this requirement, it is not necessary to zero out the si_pid field before calling waitid(). However, not all implementations follow the POSIX.1 specification on this point.

## RETURN VALUE
wait(): on success, returns the process ID of the terminated child; on failure, -1 is returned.

waitpid(): on success, returns the process ID of the child whose state has changed; if WNOHANG was specified and one or more child(ren) specified by pid exist, but have not yet changed state, then 0 is returned. On failure, -1 is returned.

waitid(): returns 0 on success or if WNOHANG was specified and no child(ren) specified by id has yet changed state; on failure, -1 is returned.

On failure, each of these calls sets errno to indicate the error.

## ERRORS
ECHILD

(for wait()) The calling process does not have any unwaited-for children.

ECHILD

(for waitpid() or waitid()) The process specified by pid (waitpid()) or idtype and id (waitid()) does not exist or is not a child of the calling process. (This can happen for one's own child if the action for SIGCHLD is set to SIG_IGN. See also the Linux Notes section about threads.)

EINTR

WNOHANG was not set and an unblocked signal or a SIGCHLD was caught; see signal(7).

EINVAL

The options argument was invalid.

## CONFORMING TO
SVr4, 4.3BSD, POSIX.1-2001.

## NOTES
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(1), (or by the nearest "subreaper" process as defined through the use of the prctl(2) PR_SET_CHILD_SUBREAPER operation); init(1) 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 behavior of setting SIGCHLD to SIG_IGN unspecified. Note that even though the default disposition of SIGCHLD is "ignore", explicitly setting the disposition to SIG_IGN results in different treatment of zombie process children.)

Linux 2.6 conforms to the POSIX requirements. 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.

### Linux notes
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 can also, since Linux 4.7, be used with waitid():

__WCLONE

Wait for "clone" children only. If omitted, then wait for "non-clone" children only. (A "clone" child is one which delivers no signal, or a signal other than SIGCHLD to its parent upon termination.) This option is ignored if __WALL is also specified.

__WALL (since Linux 2.4)

Wait for all children, regardless of type ("clone" or "non-clone").

__WNOTHREAD (since Linux 2.4)

Do not wait for children of other threads in the same thread group. This was the default before Linux 2.4.

Since Linux 4.7, the __WALL flag is automatically implied if the child is being ptraced.

### C library/kernel differences
wait() is actually a library function that (in glibc) is implemented as a call to wait4(2).

On some architectures, there is no waitpid() system call; instead, this interface is implemented via a C library wrapper function that calls wait4(2).

The raw waitid() system call takes a fifth argument, of type struct rusage *. If this argument is non-NULL, then it is used to return resource usage information about the child, in the same manner as wait4(2). See getrusage(2) for details.

## BUGS
According to POSIX.1-2008, an application calling waitid() must ensure that infop points to a siginfo_t structure (i.e., that it is a non-null pointer). On Linux, if infop is NULL, waitid() succeeds, and returns the process ID of the waited-for child. Applications should avoid relying on this inconsistent, nonstandard, and unnecessary feature.

## EXAMPLES
The following program demonstrates the use of fork(2) and waitpid(). 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(), and uses the W*() macros described above to analyze 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
$
```

### Program source

```
#include <sys/wait.h>
#include <stdint.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
int
main(int argc, char *argv[])
{

    pid_t cpid, w;

    int wstatus;

    cpid = fork();

    if (cpid == -1) {

        perror("fork");

        exit(EXIT_FAILURE);

    }

    if (cpid == 0) {            /* Code executed by child */

        printf("Child PID is %jd\n", (intmax_t) getpid());

        if (argc == 1)

            pause();                    /* Wait for signals */

        _exit(atoi(argv[1]));

    } else {                    /* Code executed by parent */

        do {

            w = waitpid(cpid, &wstatus, WUNTRACED | WCONTINUED);

            if (w == -1) {

                perror("waitpid");

                exit(EXIT_FAILURE);

            }

            if (WIFEXITED(wstatus)) {

                printf("exited, status=%d\n", WEXITSTATUS(wstatus));

            } else if (WIFSIGNALED(wstatus)) {

                printf("killed by signal %d\n", WTERMSIG(wstatus));

            } else if (WIFSTOPPED(wstatus)) {

                printf("stopped by signal %d\n", WSTOPSIG(wstatus));

            } else if (WIFCONTINUED(wstatus)) {

                printf("continued\n");

            }

        } while (!WIFEXITED(wstatus) && !WIFSIGNALED(wstatus));

        exit(EXIT_SUCCESS);

    }
}
```

## SEE ALSO
_exit(2), clone(2), fork(2), kill(2), ptrace(2), sigaction(2), signal(2), wait4(2), pthread_create(3), core(5), credentials(7), signal(7)


package: man-pages

title: wait4(2)

text:
# wait4(2)

## NAME
wait3, wait4 - wait for process to change state, BSD style

## SYNOPSIS

```
#include <sys/wait.h>
```

```
pid_t wait3(int *wstatus, int options, struct rusage *rusage);
pid_t wait4(pid_t pid, int *wstatus, int options,
            struct rusage *rusage);
```

Feature Test Macro Requirements for glibc (see feature_test_macros(7)):

wait3():

```
    Since glibc 2.26:

        _DEFAULT_SOURCE

            || (_XOPEN_SOURCE >= 500 &&

                ! (_POSIX_C_SOURCE >= 200112L

                   || _XOPEN_SOURCE >= 600))

    From glibc 2.19 to 2.25:

        _DEFAULT_SOURCE || _XOPEN_SOURCE >= 500

    Glibc 2.19 and earlier:

        _BSD_SOURCE || _XOPEN_SOURCE >= 500
```

wait4():

```
    Since glibc 2.19:

        _DEFAULT_SOURCE

    Glibc 2.19 and earlier:

        _BSD_SOURCE
```

## DESCRIPTION
These functions are nonstandard; in new programs, the use of waitpid(2) or waitid(2) is preferable.

The wait3() and wait4() system calls are similar to waitpid(2), but additionally return resource usage information about the child in the structure pointed to by rusage.

Other than the use of the rusage argument, the following wait3() call:

```
wait3(wstatus, options, rusage);
```

is equivalent to:

```
waitpid(-1, wstatus, options);
```

Similarly, the following wait4() call:

```
wait4(pid, wstatus, options, rusage);
```

is equivalent to:

```
waitpid(pid, wstatus, options);
```

In other words, wait3() waits of any child, while wait4() can be used to select a specific child, or children, on which to wait. See wait(2) for further details.

If rusage is not NULL, the struct rusage to which it points will be filled with accounting information about the child. See getrusage(2) for details.

## RETURN VALUE
As for waitpid(2).

## ERRORS
As for waitpid(2).

## CONFORMING TO
4.3BSD.

SUSv1 included a specification of wait3(); SUSv2 included wait3(), but marked it LEGACY; SUSv3 removed it.

## NOTES
Including <sys/time.h> is not required these days, but increases portability. (Indeed, <sys/resource.h> defines the rusage structure with fields of type struct timeval defined in <sys/time.h>.)

### C library/kernel differences
On Linux, wait3() is a library function implemented on top of the wait4() system call.

## SEE ALSO
fork(2), getrusage(2), sigaction(2), signal(2), wait(2), signal(7)


write

title: write(2)

summary: write to a file descriptor

text:
# write(2)

## NAME
write - write to a file descriptor

## SYNOPSIS

```
#include <unistd.h>
```

```
ssize_t write(int fd, const void *buf, size_t count);
```

## DESCRIPTION
write() writes up to count bytes from the buffer starting at buf to the file referred to by the file descriptor fd.

The number of bytes written may be less than count if, for example, there is insufficient space on the underlying physical medium, or the RLIMIT_FSIZE resource limit is encountered (see setrlimit(2)), or the call was interrupted by a signal handler after having written less than count bytes. (See also pipe(7).)

For a seekable file (i.e., one to which lseek(2) may be applied, for example, a regular file) writing takes place at the file offset, and the file offset is incremented by the number of bytes actually written. If the file was open(2)ed with O_APPEND, the file offset is first set to the end of the file before writing. The adjustment of the file offset and the write operation are performed as an atomic step.

POSIX requires that a read(2) that can be proved to occur after a write() has returned will return the new data. Note that not all filesystems are POSIX conforming.

According to POSIX.1, if count is greater than SSIZE_MAX, the result is implementation-defined; see NOTES for the upper limit on Linux.

## RETURN VALUE
On success, the number of bytes written is returned. On error, -1 is returned, and errno is set to indicate the error.

Note that a successful write() may transfer fewer than count bytes. Such partial writes can occur for various reasons; for example, because there was insufficient space on the disk device to write all of the requested bytes, or because a blocked write() to a socket, pipe, or similar was interrupted by a signal handler after it had transferred some, but before it had transferred all of the requested bytes. In the event of a partial write, the caller can make another write() call to transfer the remaining bytes. The subsequent call will either transfer further bytes or may result in an error (e.g., if the disk is now full).

If count is zero and fd refers to a regular file, then write() may return a failure status if one of the errors below is detected. If no errors are detected, or error detection is not performed, 0 is returned without causing any other effect. If count is zero and fd refers to a file other than a regular file, the results are not specified.

## ERRORS
EAGAIN

The file descriptor fd refers to a file other than a socket and has been marked nonblocking (O_NONBLOCK), and the write would block. See open(2) for further details on the O_NONBLOCK flag.

EAGAIN or EWOULDBLOCK

The file descriptor fd refers to a socket and has been marked nonblocking (O_NONBLOCK), and the write would block. POSIX.1-2001 allows either error to be returned for this case, and does not require these constants to have the same value, so a portable application should check for both possibilities.

EBADF

fd is not a valid file descriptor or is not open for writing.

EDESTADDRREQ

fd refers to a datagram socket for which a peer address has not been set using connect(2).

EDQUOT

The user's quota of disk blocks on the filesystem containing the file referred to by fd has been exhausted.

EFAULT

buf is outside your accessible address space.

EFBIG

An attempt was made to write a file that exceeds the implementation-defined maximum file size or the process's file size limit, or to write at a position past the maximum allowed offset.

EINTR

The call was interrupted by a signal before any data was written; see signal(7).

EINVAL

fd is attached to an object which is unsuitable for writing; or the file was opened with the O_DIRECT flag, and either the address specified in buf, the value specified in count, or the file offset is not suitably aligned.

EIO

A low-level I/O error occurred while modifying the inode. This error may relate to the write-back of data written by an earlier write(), which may have been issued to a different file descriptor on the same file. Since Linux 4.13, errors from write-back come with a promise that they may be reported by subsequent. write() requests, and will be reported by a subsequent fsync(2) (whether or not they were also reported by write()). An alternate cause of EIO on networked filesystems is when an advisory lock had been taken out on the file descriptor and this lock has been lost. See the Lost locks section of fcntl(2) for further details.

ENOSPC

The device containing the file referred to by fd has no room for the data.

EPERM

The operation was prevented by a file seal; see fcntl(2).

EPIPE

fd is connected to a pipe or socket whose reading end is closed. When this happens the writing process will also receive a SIGPIPE signal. (Thus, the write return value is seen only if the program catches, blocks or ignores this signal.)

Other errors may occur, depending on the object connected to fd.

## CONFORMING TO
SVr4, 4.3BSD, POSIX.1-2001.

Under SVr4 a write may be interrupted and return EINTR at any point, not just before any data is written.

## NOTES
The types size_t and ssize_t are, respectively, unsigned and signed integer data types specified by POSIX.1.

A successful return from write() does not make any guarantee that data has been committed to disk. On some filesystems, including NFS, it does not even guarantee that space has successfully been reserved for the data. In this case, some errors might be delayed until a future write(), fsync(2), or even close(2). The only way to be sure is to call fsync(2) after you are done writing all your data.

If a write() is interrupted by a signal handler before any bytes are written, then the call fails with the error EINTR; if it is interrupted after at least one byte has been written, the call succeeds, and returns the number of bytes written.

On Linux, write() (and similar system calls) will transfer at most 0x7ffff000 (2,147,479,552) bytes, returning the number of bytes actually transferred. (This is true on both 32-bit and 64-bit systems.)

An error return value while performing write() using direct I/O does not mean the entire write has failed. Partial data may be written and the data at the file offset on which the write() was attempted should be considered inconsistent.

## BUGS
According to POSIX.1-2008/SUSv4 Section XSI 2.9.7 ("Thread Interactions with Regular File Operations"):

All of the following functions shall be atomic with respect to each other in the effects specified in POSIX.1-2008 when they operate on regular files or symbolic links: ...

Among the APIs subsequently listed are write() and writev(2). And among the effects that should be atomic across threads (and processes) are updates of the file offset. However, on Linux before version 3.14, this was not the case: if two processes that share an open file description (see open(2)) perform a write() (or writev(2)) at the same time, then the I/O operations were not atomic with respect to updating the file offset, with the result that the blocks of data output by the two processes might (incorrectly) overlap. This problem was fixed in Linux 3.14.

## SEE ALSO
close(2), fcntl(2), fsync(2), ioctl(2), lseek(2), open(2), pwrite(2), read(2), select(2), writev(2), fwrite(3)