process.texi 34 KB

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