1@node Processes, Inter-Process Communication, Program Basics, Top 2@c %MENU% How to create processes and run other programs 3@chapter Processes 4 5@cindex process 6@dfn{Processes} are the primitive units for allocation of system 7resources. Each process has its own address space and (usually) one 8thread of control. A process executes a program; you can have multiple 9processes executing the same program, but each process has its own copy 10of the program within its own address space and executes it 11independently of the other copies. 12 13@cindex child process 14@cindex parent process 15Processes are organized hierarchically. Each process has a @dfn{parent 16process} which explicitly arranged to create it. The processes created 17by a given parent are called its @dfn{child processes}. A child 18inherits many of its attributes from the parent process. 19 20This chapter describes how a program can create, terminate, and control 21child processes. Actually, there are three distinct operations 22involved: creating a new child process, causing the new process to 23execute a program, and coordinating the completion of the child process 24with the original program. 25 26The @code{system} function provides a simple, portable mechanism for 27running another program; it does all three steps automatically. If you 28need more control over the details of how this is done, you can use the 29primitive functions to do each step individually instead. 30 31@menu 32* Running a Command:: The easy way to run another program. 33* Process Creation Concepts:: An overview of the hard way to do it. 34* Process Identification:: How to get the process ID of a process. 35* Creating a Process:: How to fork a child process. 36* Executing a File:: How to make a process execute another program. 37* Process Completion:: How to tell when a child process has completed. 38* Process Completion Status:: How to interpret the status value 39 returned from a child process. 40* BSD Wait Functions:: More functions, for backward compatibility. 41* Process Creation Example:: A complete example program. 42@end menu 43 44 45@node Running a Command 46@section Running a Command 47@cindex running a command 48 49The easy way to run another program is to use the @code{system} 50function. This function does all the work of running a subprogram, but 51it doesn't give you much control over the details: you have to wait 52until the subprogram terminates before you can do anything else. 53 54@deftypefun int system (const char *@var{command}) 55@standards{ISO, stdlib.h} 56@pindex sh 57@safety{@prelim{}@mtsafe{}@asunsafe{@ascuplugin{} @ascuheap{} @asulock{}}@acunsafe{@aculock{} @acsmem{}}} 58@c system @ascuplugin @ascuheap @asulock @aculock @acsmem 59@c do_system @ascuplugin @ascuheap @asulock @aculock @acsmem 60@c sigemptyset dup ok 61@c libc_lock_lock @asulock @aculock 62@c ADD_REF ok 63@c sigaction dup ok 64@c SUB_REF ok 65@c libc_lock_unlock @aculock 66@c sigaddset dup ok 67@c sigprocmask dup ok 68@c CLEANUP_HANDLER @ascuplugin @ascuheap @acsmem 69@c libc_cleanup_region_start @ascuplugin @ascuheap @acsmem 70@c pthread_cleanup_push_defer @ascuplugin @ascuheap @acsmem 71@c __pthread_testcancel @ascuplugin @ascuheap @acsmem 72@c CANCEL_ENABLED_AND_CANCELED ok 73@c do_cancel @ascuplugin @ascuheap @acsmem 74@c cancel_handler ok 75@c kill syscall ok 76@c waitpid dup ok 77@c libc_lock_lock ok 78@c sigaction dup ok 79@c libc_lock_unlock ok 80@c FORK ok 81@c clone syscall ok 82@c waitpid dup ok 83@c CLEANUP_RESET ok 84@c libc_cleanup_region_end ok 85@c pthread_cleanup_pop_restore ok 86@c SINGLE_THREAD_P ok 87@c LIBC_CANCEL_ASYNC @ascuplugin @ascuheap @acsmem 88@c libc_enable_asynccancel @ascuplugin @ascuheap @acsmem 89@c do_cancel dup @ascuplugin @ascuheap @acsmem 90@c LIBC_CANCEL_RESET ok 91@c libc_disable_asynccancel ok 92@c lll_futex_wait dup ok 93This function executes @var{command} as a shell command. In @theglibc{}, 94it always uses the default shell @code{sh} to run the command. 95In particular, it searches the directories in @code{PATH} to find 96programs to execute. The return value is @code{-1} if it wasn't 97possible to create the shell process, and otherwise is the status of the 98shell process. @xref{Process Completion}, for details on how this 99status code can be interpreted. 100 101If the @var{command} argument is a null pointer, a return value of zero 102indicates that no command processor is available. 103 104This function is a cancellation point in multi-threaded programs. This 105is a problem if the thread allocates some resources (like memory, file 106descriptors, semaphores or whatever) at the time @code{system} is 107called. If the thread gets canceled these resources stay allocated 108until the program ends. To avoid this calls to @code{system} should be 109protected using cancellation handlers. 110@c ref pthread_cleanup_push / pthread_cleanup_pop 111 112@pindex stdlib.h 113The @code{system} function is declared in the header file 114@file{stdlib.h}. 115@end deftypefun 116 117@strong{Portability Note:} Some C implementations may not have any 118notion of a command processor that can execute other programs. You can 119determine whether a command processor exists by executing 120@w{@code{system (NULL)}}; if the return value is nonzero, a command 121processor is available. 122 123The @code{popen} and @code{pclose} functions (@pxref{Pipe to a 124Subprocess}) are closely related to the @code{system} function. They 125allow the parent process to communicate with the standard input and 126output channels of the command being executed. 127 128@node Process Creation Concepts 129@section Process Creation Concepts 130 131This section gives an overview of processes and of the steps involved in 132creating a process and making it run another program. 133 134@cindex creating a process 135@cindex forking a process 136@cindex child process 137@cindex parent process 138@cindex subprocess 139A new processes is created when one of the functions 140@code{posix_spawn}, @code{fork}, @code{_Fork} or @code{vfork} is called. 141(The @code{system} and @code{popen} also create new processes internally.) 142Due to the name of the @code{fork} function, the act of creating a new 143process is sometimes called @dfn{forking} a process. Each new process 144(the @dfn{child process} or @dfn{subprocess}) is allocated a process 145ID, distinct from the process ID of the parent process. @xref{Process 146Identification}. 147 148After forking a child process, both the parent and child processes 149continue to execute normally. If you want your program to wait for a 150child process to finish executing before continuing, you must do this 151explicitly after the fork operation, by calling @code{wait} or 152@code{waitpid} (@pxref{Process Completion}). These functions give you 153limited information about why the child terminated---for example, its 154exit status code. 155 156A newly forked child process continues to execute the same program as 157its parent process, at the point where the @code{fork} or @code{_Fork} 158call returns. You can use the return value from @code{fork} or 159@code{_Fork} to tell whether the program is running in the parent process 160or the child. 161 162@cindex process image 163Having several processes run the same program is only occasionally 164useful. But the child can execute another program using one of the 165@code{exec} functions; see @ref{Executing a File}. The program that the 166process is executing is called its @dfn{process image}. Starting 167execution of a new program causes the process to forget all about its 168previous process image; when the new program exits, the process exits 169too, instead of returning to the previous process image. 170 171@node Process Identification 172@section Process Identification 173 174@cindex process ID 175Each process is named by a @dfn{process ID} number, a value of type 176@code{pid_t}. A process ID is allocated to each process when it is 177created. Process IDs are reused over time. The lifetime of a process 178ends when the parent process of the corresponding process waits on the 179process ID after the process has terminated. @xref{Process 180Completion}. (The parent process can arrange for such waiting to 181happen implicitly.) A process ID uniquely identifies a process only 182during the lifetime of the process. As a rule of thumb, this means 183that the process must still be running. 184 185Process IDs can also denote process groups and sessions. 186@xref{Job Control}. 187 188@cindex thread ID 189@cindex task ID 190@cindex thread group 191On Linux, threads created by @code{pthread_create} also receive a 192@dfn{thread ID}. The thread ID of the initial (main) thread is the 193same as the process ID of the entire process. Thread IDs for 194subsequently created threads are distinct. They are allocated from 195the same numbering space as process IDs. Process IDs and thread IDs 196are sometimes also referred to collectively as @dfn{task IDs}. In 197contrast to processes, threads are never waited for explicitly, so a 198thread ID becomes eligible for reuse as soon as a thread exits or is 199canceled. This is true even for joinable threads, not just detached 200threads. Threads are assigned to a @dfn{thread group}. In 201@theglibc{} implementation running on Linux, the process ID is the 202thread group ID of all threads in the process. 203 204You can get the process ID of a process by calling @code{getpid}. The 205function @code{getppid} returns the process ID of the parent of the 206current process (this is also known as the @dfn{parent process ID}). 207Your program should include the header files @file{unistd.h} and 208@file{sys/types.h} to use these functions. 209@pindex sys/types.h 210@pindex unistd.h 211 212@deftp {Data Type} pid_t 213@standards{POSIX.1, sys/types.h} 214The @code{pid_t} data type is a signed integer type which is capable 215of representing a process ID. In @theglibc{}, this is an @code{int}. 216@end deftp 217 218@deftypefun pid_t getpid (void) 219@standards{POSIX.1, unistd.h} 220@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}} 221The @code{getpid} function returns the process ID of the current process. 222@end deftypefun 223 224@deftypefun pid_t getppid (void) 225@standards{POSIX.1, unistd.h} 226@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}} 227The @code{getppid} function returns the process ID of the parent of the 228current process. 229@end deftypefun 230 231@deftypefun pid_t gettid (void) 232@standards{Linux, unistd.h} 233@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}} 234The @code{gettid} function returns the thread ID of the current 235thread. The returned value is obtained from the Linux kernel and is 236not subject to caching. See the discussion of thread IDs above, 237especially regarding reuse of the IDs of threads which have exited. 238 239This function is specific to Linux. 240@end deftypefun 241 242@node Creating a Process 243@section Creating a Process 244 245The @code{fork} function is the primitive for creating a process. 246It is declared in the header file @file{unistd.h}. 247@pindex unistd.h 248 249@deftypefun pid_t fork (void) 250@standards{POSIX.1, unistd.h} 251@safety{@prelim{}@mtsafe{}@asunsafe{@ascuplugin{}}@acunsafe{@aculock{}}} 252@c The posix/fork.c implementation iterates over the fork_handlers 253@c using a lock. It then takes the IO_list lock, resets the thread-local 254@c pid, and runs fork. The parent releases the lock, and runs parent 255@c handlers, and unlocks the internal lock. The child bumps the fork 256@c generation, sets the thread-local pid, resets cpu clocks, initializes 257@c the robust mutex list, the stream locks, the IO_list lock, the dynamic 258@c loader lock, runs the child handlers, reseting ref counters to 1, and 259@c initializes the fork lock. These are all safe, unless atfork 260@c handlers themselves are unsafe. 261The @code{fork} function creates a new process. 262 263If the operation is successful, there are then both parent and child 264processes and both see @code{fork} return, but with different values: it 265returns a value of @code{0} in the child process and returns the child's 266process ID in the parent process. 267 268If process creation failed, @code{fork} returns a value of @code{-1} in 269the parent process. The following @code{errno} error conditions are 270defined for @code{fork}: 271 272@table @code 273@item EAGAIN 274There aren't enough system resources to create another process, or the 275user already has too many processes running. This means exceeding the 276@code{RLIMIT_NPROC} resource limit, which can usually be increased; 277@pxref{Limits on Resources}. 278 279@item ENOMEM 280The process requires more space than the system can supply. 281@end table 282@end deftypefun 283 284The specific attributes of the child process that differ from the 285parent process are: 286 287@itemize @bullet 288@item 289The child process has its own unique process ID. 290 291@item 292The parent process ID of the child process is the process ID of its 293parent process. 294 295@item 296The child process gets its own copies of the parent process's open file 297descriptors. Subsequently changing attributes of the file descriptors 298in the parent process won't affect the file descriptors in the child, 299and vice versa. @xref{Control Operations}. However, the file position 300associated with each descriptor is shared by both processes; 301@pxref{File Position}. 302 303@item 304The elapsed processor times for the child process are set to zero; 305see @ref{Processor Time}. 306 307@item 308The child doesn't inherit file locks set by the parent process. 309@c !!! flock locks shared 310@xref{Control Operations}. 311 312@item 313The child doesn't inherit alarms set by the parent process. 314@xref{Setting an Alarm}. 315 316@item 317The set of pending signals (@pxref{Delivery of Signal}) for the child 318process is cleared. (The child process inherits its mask of blocked 319signals and signal actions from the parent process.) 320@end itemize 321 322@deftypefun pid_t _Fork (void) 323@standards{GNU, unistd.h} 324@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}} 325The @code{_Fork} function is similar to @code{fork}, but it does not invoke 326any callbacks registered with @code{pthread_atfork}, nor does it reset 327any internal state or locks (such as the @code{malloc} locks). In the 328new subprocess, only async-signal-safe functions may be called, such as 329@code{dup2} or @code{execve}. 330 331The @code{_Fork} function is an async-signal-safe replacement of @code{fork}. 332It is a GNU extension. 333 334@end deftypefun 335 336@deftypefun pid_t vfork (void) 337@standards{BSD, unistd.h} 338@safety{@prelim{}@mtsafe{}@asunsafe{@ascuplugin{}}@acunsafe{@aculock{}}} 339@c The vfork implementation proper is a safe syscall, but it may fall 340@c back to fork if the vfork syscall is not available. 341The @code{vfork} function is similar to @code{fork} but on some systems 342it is more efficient; however, there are restrictions you must follow to 343use it safely. 344 345While @code{fork} makes a complete copy of the calling process's address 346space and allows both the parent and child to execute independently, 347@code{vfork} does not make this copy. Instead, the child process 348created with @code{vfork} shares its parent's address space until it 349calls @code{_exit} or one of the @code{exec} functions. In the 350meantime, the parent process suspends execution. 351 352You must be very careful not to allow the child process created with 353@code{vfork} to modify any global data or even local variables shared 354with the parent. Furthermore, the child process cannot return from (or 355do a long jump out of) the function that called @code{vfork}! This 356would leave the parent process's control information very confused. If 357in doubt, use @code{fork} instead. 358 359Some operating systems don't really implement @code{vfork}. @Theglibc{} 360permits you to use @code{vfork} on all systems, but actually 361executes @code{fork} if @code{vfork} isn't available. If you follow 362the proper precautions for using @code{vfork}, your program will still 363work even if the system uses @code{fork} instead. 364@end deftypefun 365 366@node Executing a File 367@section Executing a File 368@cindex executing a file 369@cindex @code{exec} functions 370 371This section describes the @code{exec} family of functions, for executing 372a file as a process image. You can use these functions to make a child 373process execute a new program after it has been forked. 374 375To see the effects of @code{exec} from the point of view of the called 376program, see @ref{Program Basics}. 377 378@pindex unistd.h 379The functions in this family differ in how you specify the arguments, 380but otherwise they all do the same thing. They are declared in the 381header file @file{unistd.h}. 382 383@deftypefun int execv (const char *@var{filename}, char *const @var{argv}@t{[]}) 384@standards{POSIX.1, unistd.h} 385@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}} 386The @code{execv} function executes the file named by @var{filename} as a 387new process image. 388 389The @var{argv} argument is an array of null-terminated strings that is 390used to provide a value for the @code{argv} argument to the @code{main} 391function of the program to be executed. The last element of this array 392must be a null pointer. By convention, the first element of this array 393is the file name of the program sans directory names. @xref{Program 394Arguments}, for full details on how programs can access these arguments. 395 396The environment for the new process image is taken from the 397@code{environ} variable of the current process image; see 398@ref{Environment Variables}, for information about environments. 399@end deftypefun 400 401@deftypefun int execl (const char *@var{filename}, const char *@var{arg0}, @dots{}) 402@standards{POSIX.1, unistd.h} 403@safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}} 404This is similar to @code{execv}, but the @var{argv} strings are 405specified individually instead of as an array. A null pointer must be 406passed as the last such argument. 407@end deftypefun 408 409@deftypefun int execve (const char *@var{filename}, char *const @var{argv}@t{[]}, char *const @var{env}@t{[]}) 410@standards{POSIX.1, unistd.h} 411@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}} 412This is similar to @code{execv}, but permits you to specify the environment 413for the new program explicitly as the @var{env} argument. This should 414be an array of strings in the same format as for the @code{environ} 415variable; see @ref{Environment Access}. 416@end deftypefun 417 418@deftypefun int fexecve (int @var{fd}, char *const @var{argv}@t{[]}, char *const @var{env}@t{[]}) 419@standards{POSIX.1, unistd.h} 420@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}} 421This is similar to @code{execve}, but instead of identifying the program 422executable by its pathname, the file descriptor @var{fd} is used. The 423descriptor must have been opened with the @code{O_RDONLY} flag or (on 424Linux) the @code{O_PATH} flag. 425 426On Linux, @code{fexecve} can fail with an error of @code{ENOSYS} if 427@file{/proc} has not been mounted and the kernel lacks support for the 428underlying @code{execveat} system call. 429@end deftypefun 430 431@deftypefun int execle (const char *@var{filename}, const char *@var{arg0}, @dots{}, char *const @var{env}@t{[]}) 432@standards{POSIX.1, unistd.h} 433@safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}} 434This is similar to @code{execl}, but permits you to specify the 435environment for the new program explicitly. The environment argument is 436passed following the null pointer that marks the last @var{argv} 437argument, and should be an array of strings in the same format as for 438the @code{environ} variable. 439@end deftypefun 440 441@deftypefun int execvp (const char *@var{filename}, char *const @var{argv}@t{[]}) 442@standards{POSIX.1, unistd.h} 443@safety{@prelim{}@mtsafe{@mtsenv{}}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}} 444The @code{execvp} function is similar to @code{execv}, except that it 445searches the directories listed in the @code{PATH} environment variable 446(@pxref{Standard Environment}) to find the full file name of a 447file from @var{filename} if @var{filename} does not contain a slash. 448 449This function is useful for executing system utility programs, because 450it looks for them in the places that the user has chosen. Shells use it 451to run the commands that users type. 452@end deftypefun 453 454@deftypefun int execlp (const char *@var{filename}, const char *@var{arg0}, @dots{}) 455@standards{POSIX.1, unistd.h} 456@safety{@prelim{}@mtsafe{@mtsenv{}}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}} 457This function is like @code{execl}, except that it performs the same 458file name searching as the @code{execvp} function. 459@end deftypefun 460 461The size of the argument list and environment list taken together must 462not be greater than @code{ARG_MAX} bytes. @xref{General Limits}. On 463@gnuhurdsystems{}, the size (which compares against @code{ARG_MAX}) 464includes, for each string, the number of characters in the string, plus 465the size of a @code{char *}, plus one, rounded up to a multiple of the 466size of a @code{char *}. Other systems may have somewhat different 467rules for counting. 468 469These functions normally don't return, since execution of a new program 470causes the currently executing program to go away completely. A value 471of @code{-1} is returned in the event of a failure. In addition to the 472usual file name errors (@pxref{File Name Errors}), the following 473@code{errno} error conditions are defined for these functions: 474 475@table @code 476@item E2BIG 477The combined size of the new program's argument list and environment 478list is larger than @code{ARG_MAX} bytes. @gnuhurdsystems{} have no 479specific limit on the argument list size, so this error code cannot 480result, but you may get @code{ENOMEM} instead if the arguments are too 481big for available memory. 482 483@item ENOEXEC 484The specified file can't be executed because it isn't in the right format. 485 486@item ENOMEM 487Executing the specified file requires more storage than is available. 488@end table 489 490If execution of the new file succeeds, it updates the access time field 491of the file as if the file had been read. @xref{File Times}, for more 492details about access times of files. 493 494The point at which the file is closed again is not specified, but 495is at some point before the process exits or before another process 496image is executed. 497 498Executing a new process image completely changes the contents of memory, 499copying only the argument and environment strings to new locations. But 500many other attributes of the process are unchanged: 501 502@itemize @bullet 503@item 504The process ID and the parent process ID. @xref{Process Creation Concepts}. 505 506@item 507Session and process group membership. @xref{Concepts of Job Control}. 508 509@item 510Real user ID and group ID, and supplementary group IDs. @xref{Process 511Persona}. 512 513@item 514Pending alarms. @xref{Setting an Alarm}. 515 516@item 517Current working directory and root directory. @xref{Working 518Directory}. On @gnuhurdsystems{}, the root directory is not copied when 519executing a setuid program; instead the system default root directory 520is used for the new program. 521 522@item 523File mode creation mask. @xref{Setting Permissions}. 524 525@item 526Process signal mask; see @ref{Process Signal Mask}. 527 528@item 529Pending signals; see @ref{Blocking Signals}. 530 531@item 532Elapsed processor time associated with the process; see @ref{Processor Time}. 533@end itemize 534 535If the set-user-ID and set-group-ID mode bits of the process image file 536are set, this affects the effective user ID and effective group ID 537(respectively) of the process. These concepts are discussed in detail 538in @ref{Process Persona}. 539 540Signals that are set to be ignored in the existing process image are 541also set to be ignored in the new process image. All other signals are 542set to the default action in the new process image. For more 543information about signals, see @ref{Signal Handling}. 544 545File descriptors open in the existing process image remain open in the 546new process image, unless they have the @code{FD_CLOEXEC} 547(close-on-exec) flag set. The files that remain open inherit all 548attributes of the open file descriptors from the existing process image, 549including file locks. File descriptors are discussed in @ref{Low-Level I/O}. 550 551Streams, by contrast, cannot survive through @code{exec} functions, 552because they are located in the memory of the process itself. The new 553process image has no streams except those it creates afresh. Each of 554the streams in the pre-@code{exec} process image has a descriptor inside 555it, and these descriptors do survive through @code{exec} (provided that 556they do not have @code{FD_CLOEXEC} set). The new process image can 557reconnect these to new streams using @code{fdopen} (@pxref{Descriptors 558and Streams}). 559 560@node Process Completion 561@section Process Completion 562@cindex process completion 563@cindex waiting for completion of child process 564@cindex testing exit status of child process 565 566The functions described in this section are used to wait for a child 567process to terminate or stop, and determine its status. These functions 568are declared in the header file @file{sys/wait.h}. 569@pindex sys/wait.h 570 571@deftypefun pid_t waitpid (pid_t @var{pid}, int *@var{status-ptr}, int @var{options}) 572@standards{POSIX.1, sys/wait.h} 573@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}} 574The @code{waitpid} function is used to request status information from a 575child process whose process ID is @var{pid}. Normally, the calling 576process is suspended until the child process makes status information 577available by terminating. 578 579Other values for the @var{pid} argument have special interpretations. A 580value of @code{-1} or @code{WAIT_ANY} requests status information for 581any child process; a value of @code{0} or @code{WAIT_MYPGRP} requests 582information for any child process in the same process group as the 583calling process; and any other negative value @minus{} @var{pgid} 584requests information for any child process whose process group ID is 585@var{pgid}. 586 587If status information for a child process is available immediately, this 588function returns immediately without waiting. If more than one eligible 589child process has status information available, one of them is chosen 590randomly, and its status is returned immediately. To get the status 591from the other eligible child processes, you need to call @code{waitpid} 592again. 593 594The @var{options} argument is a bit mask. Its value should be the 595bitwise OR (that is, the @samp{|} operator) of zero or more of the 596@code{WNOHANG} and @code{WUNTRACED} flags. You can use the 597@code{WNOHANG} flag to indicate that the parent process shouldn't wait; 598and the @code{WUNTRACED} flag to request status information from stopped 599processes as well as processes that have terminated. 600 601The status information from the child process is stored in the object 602that @var{status-ptr} points to, unless @var{status-ptr} is a null pointer. 603 604This function is a cancellation point in multi-threaded programs. This 605is a problem if the thread allocates some resources (like memory, file 606descriptors, semaphores or whatever) at the time @code{waitpid} is 607called. If the thread gets canceled these resources stay allocated 608until the program ends. To avoid this calls to @code{waitpid} should be 609protected using cancellation handlers. 610@c ref pthread_cleanup_push / pthread_cleanup_pop 611 612The return value is normally the process ID of the child process whose 613status is reported. If there are child processes but none of them is 614waiting to be noticed, @code{waitpid} will block until one is. However, 615if the @code{WNOHANG} option was specified, @code{waitpid} will return 616zero instead of blocking. 617 618If a specific PID to wait for was given to @code{waitpid}, it will 619ignore all other children (if any). Therefore if there are children 620waiting to be noticed but the child whose PID was specified is not one 621of them, @code{waitpid} will block or return zero as described above. 622 623A value of @code{-1} is returned in case of error. The following 624@code{errno} error conditions are defined for this function: 625 626@table @code 627@item EINTR 628The function was interrupted by delivery of a signal to the calling 629process. @xref{Interrupted Primitives}. 630 631@item ECHILD 632There are no child processes to wait for, or the specified @var{pid} 633is not a child of the calling process. 634 635@item EINVAL 636An invalid value was provided for the @var{options} argument. 637@end table 638@end deftypefun 639 640These symbolic constants are defined as values for the @var{pid} argument 641to the @code{waitpid} function. 642 643@comment Extra blank lines make it look better. 644@vtable @code 645@item WAIT_ANY 646 647This constant macro (whose value is @code{-1}) specifies that 648@code{waitpid} should return status information about any child process. 649 650 651@item WAIT_MYPGRP 652This constant (with value @code{0}) specifies that @code{waitpid} should 653return status information about any child process in the same process 654group as the calling process. 655@end vtable 656 657These symbolic constants are defined as flags for the @var{options} 658argument to the @code{waitpid} function. You can bitwise-OR the flags 659together to obtain a value to use as the argument. 660 661@vtable @code 662@item WNOHANG 663 664This flag specifies that @code{waitpid} should return immediately 665instead of waiting, if there is no child process ready to be noticed. 666 667@item WUNTRACED 668 669This flag specifies that @code{waitpid} should report the status of any 670child processes that have been stopped as well as those that have 671terminated. 672@end vtable 673 674@deftypefun pid_t wait (int *@var{status-ptr}) 675@standards{POSIX.1, sys/wait.h} 676@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}} 677This is a simplified version of @code{waitpid}, and is used to wait 678until any one child process terminates. The call: 679 680@smallexample 681wait (&status) 682@end smallexample 683 684@noindent 685is exactly equivalent to: 686 687@smallexample 688waitpid (-1, &status, 0) 689@end smallexample 690 691This function is a cancellation point in multi-threaded programs. This 692is a problem if the thread allocates some resources (like memory, file 693descriptors, semaphores or whatever) at the time @code{wait} is 694called. If the thread gets canceled these resources stay allocated 695until the program ends. To avoid this calls to @code{wait} should be 696protected using cancellation handlers. 697@c ref pthread_cleanup_push / pthread_cleanup_pop 698@end deftypefun 699 700@deftypefun pid_t wait4 (pid_t @var{pid}, int *@var{status-ptr}, int @var{options}, struct rusage *@var{usage}) 701@standards{BSD, sys/wait.h} 702@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}} 703If @var{usage} is a null pointer, @code{wait4} is equivalent to 704@code{waitpid (@var{pid}, @var{status-ptr}, @var{options})}. 705 706If @var{usage} is not null, @code{wait4} stores usage figures for the 707child process in @code{*@var{rusage}} (but only if the child has 708terminated, not if it has stopped). @xref{Resource Usage}. 709 710This function is a BSD extension. 711@end deftypefun 712 713Here's an example of how to use @code{waitpid} to get the status from 714all child processes that have terminated, without ever waiting. This 715function is designed to be a handler for @code{SIGCHLD}, the signal that 716indicates that at least one child process has terminated. 717 718@smallexample 719@group 720void 721sigchld_handler (int signum) 722@{ 723 int pid, status, serrno; 724 serrno = errno; 725 while (1) 726 @{ 727 pid = waitpid (WAIT_ANY, &status, WNOHANG); 728 if (pid < 0) 729 @{ 730 perror ("waitpid"); 731 break; 732 @} 733 if (pid == 0) 734 break; 735 notice_termination (pid, status); 736 @} 737 errno = serrno; 738@} 739@end group 740@end smallexample 741 742@node Process Completion Status 743@section Process Completion Status 744 745If the exit status value (@pxref{Program Termination}) of the child 746process is zero, then the status value reported by @code{waitpid} or 747@code{wait} is also zero. You can test for other kinds of information 748encoded in the returned status value using the following macros. 749These macros are defined in the header file @file{sys/wait.h}. 750@pindex sys/wait.h 751 752@deftypefn Macro int WIFEXITED (int @var{status}) 753@standards{POSIX.1, sys/wait.h} 754@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}} 755This macro returns a nonzero value if the child process terminated 756normally with @code{exit} or @code{_exit}. 757@end deftypefn 758 759@deftypefn Macro int WEXITSTATUS (int @var{status}) 760@standards{POSIX.1, sys/wait.h} 761@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}} 762If @code{WIFEXITED} is true of @var{status}, this macro returns the 763low-order 8 bits of the exit status value from the child process. 764@xref{Exit Status}. 765@end deftypefn 766 767@deftypefn Macro int WIFSIGNALED (int @var{status}) 768@standards{POSIX.1, sys/wait.h} 769@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}} 770This macro returns a nonzero value if the child process terminated 771because it received a signal that was not handled. 772@xref{Signal Handling}. 773@end deftypefn 774 775@deftypefn Macro int WTERMSIG (int @var{status}) 776@standards{POSIX.1, sys/wait.h} 777@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}} 778If @code{WIFSIGNALED} is true of @var{status}, this macro returns the 779signal number of the signal that terminated the child process. 780@end deftypefn 781 782@deftypefn Macro int WCOREDUMP (int @var{status}) 783@standards{BSD, sys/wait.h} 784@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}} 785This macro returns a nonzero value if the child process terminated 786and produced a core dump. 787@end deftypefn 788 789@deftypefn Macro int WIFSTOPPED (int @var{status}) 790@standards{POSIX.1, sys/wait.h} 791@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}} 792This macro returns a nonzero value if the child process is stopped. 793@end deftypefn 794 795@deftypefn Macro int WSTOPSIG (int @var{status}) 796@standards{POSIX.1, sys/wait.h} 797@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}} 798If @code{WIFSTOPPED} is true of @var{status}, this macro returns the 799signal number of the signal that caused the child process to stop. 800@end deftypefn 801 802 803@node BSD Wait Functions 804@section BSD Process Wait Function 805 806@Theglibc{} also provides the @code{wait3} function for compatibility 807with BSD. This function is declared in @file{sys/wait.h}. It is the 808predecessor to @code{wait4}, which is more flexible. @code{wait3} is 809now obsolete. 810@pindex sys/wait.h 811 812@deftypefun pid_t wait3 (int *@var{status-ptr}, int @var{options}, struct rusage *@var{usage}) 813@standards{BSD, sys/wait.h} 814@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}} 815If @var{usage} is a null pointer, @code{wait3} is equivalent to 816@code{waitpid (-1, @var{status-ptr}, @var{options})}. 817 818If @var{usage} is not null, @code{wait3} stores usage figures for the 819child process in @code{*@var{rusage}} (but only if the child has 820terminated, not if it has stopped). @xref{Resource Usage}. 821@end deftypefun 822 823@node Process Creation Example 824@section Process Creation Example 825 826Here is an example program showing how you might write a function 827similar to the built-in @code{system}. It executes its @var{command} 828argument using the equivalent of @samp{sh -c @var{command}}. 829 830@smallexample 831#include <stddef.h> 832#include <stdlib.h> 833#include <unistd.h> 834#include <sys/types.h> 835#include <sys/wait.h> 836 837/* @r{Execute the command using this shell program.} */ 838#define SHELL "/bin/sh" 839 840@group 841int 842my_system (const char *command) 843@{ 844 int status; 845 pid_t pid; 846@end group 847 848 pid = fork (); 849 if (pid == 0) 850 @{ 851 /* @r{This is the child process. Execute the shell command.} */ 852 execl (SHELL, SHELL, "-c", command, NULL); 853 _exit (EXIT_FAILURE); 854 @} 855 else if (pid < 0) 856 /* @r{The fork failed. Report failure.} */ 857 status = -1; 858 else 859 /* @r{This is the parent process. Wait for the child to complete.} */ 860 if (waitpid (pid, &status, 0) != pid) 861 status = -1; 862 return status; 863@} 864@end smallexample 865 866@comment Yes, this example has been tested. 867 868There are a couple of things you should pay attention to in this 869example. 870 871Remember that the first @code{argv} argument supplied to the program 872represents the name of the program being executed. That is why, in the 873call to @code{execl}, @code{SHELL} is supplied once to name the program 874to execute and a second time to supply a value for @code{argv[0]}. 875 876The @code{execl} call in the child process doesn't return if it is 877successful. If it fails, you must do something to make the child 878process terminate. Just returning a bad status code with @code{return} 879would leave two processes running the original program. Instead, the 880right behavior is for the child process to report failure to its parent 881process. 882 883Call @code{_exit} to accomplish this. The reason for using @code{_exit} 884instead of @code{exit} is to avoid flushing fully buffered streams such 885as @code{stdout}. The buffers of these streams probably contain data 886that was copied from the parent process by the @code{fork}, data that 887will be output eventually by the parent process. Calling @code{exit} in 888the child would output the data twice. @xref{Termination Internals}. 889