Colophon
This page is part of release 3.14 of the Linux
man-pages
project.
A description of the project,
and information about reporting bugs,
can be found at
Conforming to
SVr4, 4.3BSD, POSIX.1-2001.
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).
Index
- NAME
- SYNOPSIS
- DESCRIPTION
- wait() and waitpid()
- waitid()
- RETURN VALUE
- ERRORS
- CONFORMING TO
- NOTES
- Linux Notes
- EXAMPLE
- Program source
- SEE ALSO
- COLOPHON
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 cannot 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
SIGCHLDto its parent upon termination.)
This option is ignored if
__WALLis 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.
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
(8),
which automatically performs a wait to remove the zombies.
Program source
#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 %ldn", (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=%dn", WEXITSTATUS(status)); } else if (WIFSIGNALED(status)) { printf("killed by signal %dn", WTERMSIG(status)); } else if (WIFSTOPPED(status)) { printf("stopped by signal %dn", WSTOPSIG(status)); } else if (WIFCONTINUED(status)) { printf("continuedn"); } } while (!WIFEXITED(status) && !WIFSIGNALED(status)); exit(EXIT_SUCCESS); } }
See also
_exit
(2),
clone
(2),
fork
(2),
kill
(2),
ptrace
(2),
sigaction
(2),
signal
(2),
wait4
(2),
pthread_create
(3),
credentials
(7),
signal
(7)
Synopsis
#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);
Feature Test Macro Requirements for glibc (see
feature_test_macros(7)):
waitid():
_SVID_SOURCE || _XOPEN_SOURCE
Wait() and waitpid()
The
wait
()
system call suspends execution of the calling 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 calling process 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:
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
tracedchildren 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
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()!):
- WIFEXITED(status)
- returns true if the child terminated normally, that is,
by calling
exit(3)or
_exit(2),or by returning from main().
- WEXITSTATUS(status)
- returns the exit status of the child.
This consists of the least significant 8 bits of the
statusargument 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 only be employed if
WIFEXITEDreturned true.
- WIFSIGNALED(status)
- returns true if the child process was terminated by a signal.
- WTERMSIG(status)
- returns the number of the signal that caused the child process to
terminate.
This macro should only be employed if
WIFSIGNALEDreturned true.
- WCOREDUMP(status)
- returns true if the child produced a core dump.
This macro should only be employed if
WIFSIGNALEDreturned true.
This macro is not specified in POSIX.1-2001 and is not available on
some Unix implementations (e.g., AIX, SunOS).
Only use this enclosed in #ifdef WCOREDUMP … #endif. - WIFSTOPPED(status)
- returns true if the child process was stopped by delivery of a signal;
this is only possible if the call was done using
WUNTRACEDor when the child is being traced (see
ptrace(2)). - WSTOPSIG(status)
- returns the number of the signal which caused the child to stop.
This macro should only be employed if
WIFSTOPPEDreturned true.
- WIFCONTINUED(status)
- (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_PGID
- Wait for any child whose process group ID matches
id. - idtype == P_ALL
- Wait for any child;
idis 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:
Команда call или start с параметром / wait – 5 ответов
Это то, что я обнаружил при параллельном запуске пакетных файлов (несколько экземпляров одного и того же файла bat одновременно с разными входными параметрами):
Предположим, что у вас есть exe файл, который выполняет длинную задачу, называемую
LongRunningTask.exe
Если вы вызываете exe непосредственно из файла bat, только первый вызов LongRunningTask будет завершен, а остальная часть получит ошибку ОС “Файл уже используется процессом”
Если вы используете эту команду:
start/B/WAIT “” LongRunningTask.exe “” параметры”
Вы сможете запускать несколько экземпляров bat и exe, все еще ожидая завершения задачи до того, как bat продолжит выполнение оставшихся команд. Параметр /B состоит в том, чтобы избежать создания другого окна, для выполнения команды нужно использовать пустые кавычки, см. Ссылку ниже.
Обратите внимание: если вы не используете /WAIT в начале, LongRunningTask будет выполняться одновременно с оставшимися командами в пакетном файле, поэтому может возникнуть проблема, если одна из этих команд требует вывода LongRunningTask
Возобновление:
Это не может работать параллельно:
- вызов LongRunningTask.exe
Это будет работать параллельно и будет нормально, поскольку нет зависимостей между выводами команды и остальной частью файла bat:
- start/B “” LongRunningTask.exe “” параметры”
Это будет работать параллельно и дождитесь завершения задачи, поэтому вы можете использовать вывод:
- start/B/WAIT “” LongRunningTask.exe “” параметры”
Ссылка для команды запуска: Как запустить программу из пакетного файла, не покидая консоль после запуска программы?


