process.texi 37 KB

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