1 @node Processes, Job Control, Process Startup, Top
2 @c %MENU% How to create processes and run other programs
6 @dfn{Processes} are the primitive units for allocation of system
7 resources. Each process has its own address space and (usually) one
8 thread of control. A process executes a program; you can have multiple
9 processes executing the same program, but each process has its own copy
10 of the program within its own address space and executes it
11 independently of the other copies.
14 @cindex parent process
15 Processes are organized hierarchically. Each process has a @dfn{parent
16 process} which explicitly arranged to create it. The processes created
17 by a given parent are called its @dfn{child processes}. A child
18 inherits many of its attributes from the parent process.
20 This chapter describes how a program can create, terminate, and control
21 child processes. Actually, there are three distinct operations
22 involved: creating a new child process, causing the new process to
23 execute a program, and coordinating the completion of the child process
24 with the original program.
26 The @code{system} function provides a simple, portable mechanism for
27 running another program; it does all three steps automatically. If you
28 need more control over the details of how this is done, you can use the
29 primitive functions to do each step individually instead.
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.
45 @node Running a Command
46 @section Running a Command
47 @cindex running a command
49 The easy way to run another program is to use the @code{system}
50 function. This function does all the work of running a subprogram, but
51 it doesn't give you much control over the details: you have to wait
52 until the subprogram terminates before you can do anything else.
56 @deftypefun int system (const char *@var{command})
58 This function executes @var{command} as a shell command. In the GNU C
59 library, it always uses the default shell @code{sh} to run the command.
60 In particular, it searches the directories in @code{PATH} to find
61 programs to execute. The return value is @code{-1} if it wasn't
62 possible to create the shell process, and otherwise is the status of the
63 shell process. @xref{Process Completion}, for details on how this
64 status code can be interpreted.
66 If the @var{command} argument is a null pointer a non-zero return value
67 indicates that a command processor is available and this function can be
70 This function is a cancelation point in multi-threaded programs. This
71 is a problem if the thread allocates some resources (like memory, file
72 descriptors, semaphores or whatever) at the time @code{system} is
73 called. If the thread gets canceled these resources stay allocated
74 until the program ends. To avoid this calls to @code{system} should be
75 protected using cancelation handlers.
76 @c ref pthread_cleanup_push / pthread_cleanup_pop
79 The @code{system} function is declared in the header file
83 @strong{Portability Note:} Some C implementations may not have any
84 notion of a command processor that can execute other programs. You can
85 determine whether a command processor exists by executing
86 @w{@code{system (NULL)}}; if the return value is nonzero, a command
87 processor is available.
89 The @code{popen} and @code{pclose} functions (@pxref{Pipe to a
90 Subprocess}) are closely related to the @code{system} function. They
91 allow the parent process to communicate with the standard input and
92 output channels of the command being executed.
94 @node Process Creation Concepts
95 @section Process Creation Concepts
97 This section gives an overview of processes and of the steps involved in
98 creating a process and making it run another program.
101 @cindex process lifetime
102 Each process is named by a @dfn{process ID} number. A unique process ID
103 is allocated to each process when it is created. The @dfn{lifetime} of
104 a process ends when its termination is reported to its parent process;
105 at that time, all of the process resources, including its process ID,
108 @cindex creating a process
109 @cindex forking a process
110 @cindex child process
111 @cindex parent process
112 Processes are created with the @code{fork} system call (so the operation
113 of creating a new process is sometimes called @dfn{forking} a process).
114 The @dfn{child process} created by @code{fork} is a copy of the original
115 @dfn{parent process}, except that it has its own process ID.
117 After forking a child process, both the parent and child processes
118 continue to execute normally. If you want your program to wait for a
119 child process to finish executing before continuing, you must do this
120 explicitly after the fork operation, by calling @code{wait} or
121 @code{waitpid} (@pxref{Process Completion}). These functions give you
122 limited information about why the child terminated---for example, its
125 A newly forked child process continues to execute the same program as
126 its parent process, at the point where the @code{fork} call returns.
127 You can use the return value from @code{fork} to tell whether the program
128 is running in the parent process or the child.
130 @cindex process image
131 Having several processes run the same program is only occasionally
132 useful. But the child can execute another program using one of the
133 @code{exec} functions; see @ref{Executing a File}. The program that the
134 process is executing is called its @dfn{process image}. Starting
135 execution of a new program causes the process to forget all about its
136 previous process image; when the new program exits, the process exits
137 too, instead of returning to the previous process image.
139 @node Process Identification
140 @section Process Identification
142 The @code{pid_t} data type represents process IDs. You can get the
143 process ID of a process by calling @code{getpid}. The function
144 @code{getppid} returns the process ID of the parent of the current
145 process (this is also known as the @dfn{parent process ID}). Your
146 program should include the header files @file{unistd.h} and
147 @file{sys/types.h} to use these functions.
153 @deftp {Data Type} pid_t
154 The @code{pid_t} data type is a signed integer type which is capable
155 of representing a process ID. In the GNU library, this is an @code{int}.
160 @deftypefun pid_t getpid (void)
161 The @code{getpid} function returns the process ID of the current process.
166 @deftypefun pid_t getppid (void)
167 The @code{getppid} function returns the process ID of the parent of the
171 @node Creating a Process
172 @section Creating a Process
174 The @code{fork} function is the primitive for creating a process.
175 It is declared in the header file @file{unistd.h}.
180 @deftypefun pid_t fork (void)
181 The @code{fork} function creates a new process.
183 If the operation is successful, there are then both parent and child
184 processes and both see @code{fork} return, but with different values: it
185 returns a value of @code{0} in the child process and returns the child's
186 process ID in the parent process.
188 If process creation failed, @code{fork} returns a value of @code{-1} in
189 the parent process. The following @code{errno} error conditions are
190 defined for @code{fork}:
194 There aren't enough system resources to create another process, or the
195 user already has too many processes running. This means exceeding the
196 @code{RLIMIT_NPROC} resource limit, which can usually be increased;
197 @pxref{Limits on Resources}.
200 The process requires more space than the system can supply.
204 The specific attributes of the child process that differ from the
209 The child process has its own unique process ID.
212 The parent process ID of the child process is the process ID of its
216 The child process gets its own copies of the parent process's open file
217 descriptors. Subsequently changing attributes of the file descriptors
218 in the parent process won't affect the file descriptors in the child,
219 and vice versa. @xref{Control Operations}. However, the file position
220 associated with each descriptor is shared by both processes;
221 @pxref{File Position}.
224 The elapsed processor times for the child process are set to zero;
225 see @ref{Processor Time}.
228 The child doesn't inherit file locks set by the parent process.
229 @c !!! flock locks shared
230 @xref{Control Operations}.
233 The child doesn't inherit alarms set by the parent process.
234 @xref{Setting an Alarm}.
237 The set of pending signals (@pxref{Delivery of Signal}) for the child
238 process is cleared. (The child process inherits its mask of blocked
239 signals and signal actions from the parent process.)
245 @deftypefun pid_t vfork (void)
246 The @code{vfork} function is similar to @code{fork} but on systems it
247 is more efficient; however, there are restrictions you must follow to
250 While @code{fork} makes a complete copy of the calling process's
251 address space and allows both the parent and child to execute
252 independently, @code{vfork} does not make this copy. Instead, the
253 child process created with @code{vfork} shares its parent's address
254 space until it calls exits or one of the @code{exec} functions. In the
255 meantime, the parent process suspends execution.
257 You must be very careful not to allow the child process created with
258 @code{vfork} to modify any global data or even local variables shared
259 with the parent. Furthermore, the child process cannot return from (or
260 do a long jump out of) the function that called @code{vfork}! This
261 would leave the parent process's control information very confused. If
262 in doubt, use @code{fork} instead.
264 Some operating systems don't really implement @code{vfork}. The GNU C
265 library permits you to use @code{vfork} on all systems, but actually
266 executes @code{fork} if @code{vfork} isn't available. If you follow
267 the proper precautions for using @code{vfork}, your program will still
268 work even if the system uses @code{fork} instead.
271 @node Executing a File
272 @section Executing a File
273 @cindex executing a file
274 @cindex @code{exec} functions
276 This section describes the @code{exec} family of functions, for executing
277 a file as a process image. You can use these functions to make a child
278 process execute a new program after it has been forked.
281 The functions in this family differ in how you specify the arguments,
282 but otherwise they all do the same thing. They are declared in the
283 header file @file{unistd.h}.
287 @deftypefun int execv (const char *@var{filename}, char *const @var{argv}@t{[]})
288 The @code{execv} function executes the file named by @var{filename} as a
291 The @var{argv} argument is an array of null-terminated strings that is
292 used to provide a value for the @code{argv} argument to the @code{main}
293 function of the program to be executed. The last element of this array
294 must be a null pointer. By convention, the first element of this array
295 is the file name of the program sans directory names. @xref{Program
296 Arguments}, for full details on how programs can access these arguments.
298 The environment for the new process image is taken from the
299 @code{environ} variable of the current process image; see
300 @ref{Environment Variables}, for information about environments.
305 @deftypefun int execl (const char *@var{filename}, const char *@var{arg0}, @dots{})
306 This is similar to @code{execv}, but the @var{argv} strings are
307 specified individually instead of as an array. A null pointer must be
308 passed as the last such argument.
313 @deftypefun int execve (const char *@var{filename}, char *const @var{argv}@t{[]}, char *const @var{env}@t{[]})
314 This is similar to @code{execv}, but permits you to specify the environment
315 for the new program explicitly as the @var{env} argument. This should
316 be an array of strings in the same format as for the @code{environ}
317 variable; see @ref{Environment Access}.
322 @deftypefun int execle (const char *@var{filename}, const char *@var{arg0}, char *const @var{env}@t{[]}, @dots{})
323 This is similar to @code{execl}, but permits you to specify the
324 environment for the new program explicitly. The environment argument is
325 passed following the null pointer that marks the last @var{argv}
326 argument, and should be an array of strings in the same format as for
327 the @code{environ} variable.
332 @deftypefun int execvp (const char *@var{filename}, char *const @var{argv}@t{[]})
333 The @code{execvp} function is similar to @code{execv}, except that it
334 searches the directories listed in the @code{PATH} environment variable
335 (@pxref{Standard Environment}) to find the full file name of a
336 file from @var{filename} if @var{filename} does not contain a slash.
338 This function is useful for executing system utility programs, because
339 it looks for them in the places that the user has chosen. Shells use it
340 to run the commands that users type.
345 @deftypefun int execlp (const char *@var{filename}, const char *@var{arg0}, @dots{})
346 This function is like @code{execl}, except that it performs the same
347 file name searching as the @code{execvp} function.
350 The size of the argument list and environment list taken together must
351 not be greater than @code{ARG_MAX} bytes. @xref{General Limits}. In
352 the GNU system, the size (which compares against @code{ARG_MAX})
353 includes, for each string, the number of characters in the string, plus
354 the size of a @code{char *}, plus one, rounded up to a multiple of the
355 size of a @code{char *}. Other systems may have somewhat different
358 These functions normally don't return, since execution of a new program
359 causes the currently executing program to go away completely. A value
360 of @code{-1} is returned in the event of a failure. In addition to the
361 usual file name errors (@pxref{File Name Errors}), the following
362 @code{errno} error conditions are defined for these functions:
366 The combined size of the new program's argument list and environment
367 list is larger than @code{ARG_MAX} bytes. The GNU system has no
368 specific limit on the argument list size, so this error code cannot
369 result, but you may get @code{ENOMEM} instead if the arguments are too
370 big for available memory.
373 The specified file can't be executed because it isn't in the right format.
376 Executing the specified file requires more storage than is available.
379 If execution of the new file succeeds, it updates the access time field
380 of the file as if the file had been read. @xref{File Times}, for more
381 details about access times of files.
383 The point at which the file is closed again is not specified, but
384 is at some point before the process exits or before another process
387 Executing a new process image completely changes the contents of memory,
388 copying only the argument and environment strings to new locations. But
389 many other attributes of the process are unchanged:
393 The process ID and the parent process ID. @xref{Process Creation Concepts}.
396 Session and process group membership. @xref{Concepts of Job Control}.
399 Real user ID and group ID, and supplementary group IDs. @xref{Process
403 Pending alarms. @xref{Setting an Alarm}.
406 Current working directory and root directory. @xref{Working
407 Directory}. In the GNU system, the root directory is not copied when
408 executing a setuid program; instead the system default root directory
409 is used for the new program.
412 File mode creation mask. @xref{Setting Permissions}.
415 Process signal mask; see @ref{Process Signal Mask}.
418 Pending signals; see @ref{Blocking Signals}.
421 Elapsed processor time associated with the process; see @ref{Processor Time}.
424 If the set-user-ID and set-group-ID mode bits of the process image file
425 are set, this affects the effective user ID and effective group ID
426 (respectively) of the process. These concepts are discussed in detail
427 in @ref{Process Persona}.
429 Signals that are set to be ignored in the existing process image are
430 also set to be ignored in the new process image. All other signals are
431 set to the default action in the new process image. For more
432 information about signals, see @ref{Signal Handling}.
434 File descriptors open in the existing process image remain open in the
435 new process image, unless they have the @code{FD_CLOEXEC}
436 (close-on-exec) flag set. The files that remain open inherit all
437 attributes of the open file description from the existing process image,
438 including file locks. File descriptors are discussed in @ref{Low-Level I/O}.
440 Streams, by contrast, cannot survive through @code{exec} functions,
441 because they are located in the memory of the process itself. The new
442 process image has no streams except those it creates afresh. Each of
443 the streams in the pre-@code{exec} process image has a descriptor inside
444 it, and these descriptors do survive through @code{exec} (provided that
445 they do not have @code{FD_CLOEXEC} set). The new process image can
446 reconnect these to new streams using @code{fdopen} (@pxref{Descriptors
449 @node Process Completion
450 @section Process Completion
451 @cindex process completion
452 @cindex waiting for completion of child process
453 @cindex testing exit status of child process
455 The functions described in this section are used to wait for a child
456 process to terminate or stop, and determine its status. These functions
457 are declared in the header file @file{sys/wait.h}.
462 @deftypefun pid_t waitpid (pid_t @var{pid}, int *@var{status-ptr}, int @var{options})
463 The @code{waitpid} function is used to request status information from a
464 child process whose process ID is @var{pid}. Normally, the calling
465 process is suspended until the child process makes status information
466 available by terminating.
468 Other values for the @var{pid} argument have special interpretations. A
469 value of @code{-1} or @code{WAIT_ANY} requests status information for
470 any child process; a value of @code{0} or @code{WAIT_MYPGRP} requests
471 information for any child process in the same process group as the
472 calling process; and any other negative value @minus{} @var{pgid}
473 requests information for any child process whose process group ID is
476 If status information for a child process is available immediately, this
477 function returns immediately without waiting. If more than one eligible
478 child process has status information available, one of them is chosen
479 randomly, and its status is returned immediately. To get the status
480 from the other eligible child processes, you need to call @code{waitpid}
483 The @var{options} argument is a bit mask. Its value should be the
484 bitwise OR (that is, the @samp{|} operator) of zero or more of the
485 @code{WNOHANG} and @code{WUNTRACED} flags. You can use the
486 @code{WNOHANG} flag to indicate that the parent process shouldn't wait;
487 and the @code{WUNTRACED} flag to request status information from stopped
488 processes as well as processes that have terminated.
490 The status information from the child process is stored in the object
491 that @var{status-ptr} points to, unless @var{status-ptr} is a null pointer.
493 This function is a cancelation point in multi-threaded programs. This
494 is a problem if the thread allocates some resources (like memory, file
495 descriptors, semaphores or whatever) at the time @code{waitpid} is
496 called. If the thread gets canceled these resources stay allocated
497 until the program ends. To avoid this calls to @code{waitpid} should be
498 protected using cancelation handlers.
499 @c ref pthread_cleanup_push / pthread_cleanup_pop
501 The return value is normally the process ID of the child process whose
502 status is reported. If there are child processes but none of them is
503 waiting to be noticed, @code{waitpid} will block until one is. However,
504 if the @code{WNOHANG} option was specified, @code{waitpid} will return
505 zero instead of blocking.
507 If a specific PID to wait for was given to @code{waitpid}, it will
508 ignore all other children (if any). Therefore if there are children
509 waiting to be noticed but the child whose PID was specified is not one
510 of them, @code{waitpid} will block or return zero as described above.
512 A value of @code{-1} is returned in case of error. The following
513 @code{errno} error conditions are defined for this function:
517 The function was interrupted by delivery of a signal to the calling
518 process. @xref{Interrupted Primitives}.
521 There are no child processes to wait for, or the specified @var{pid}
522 is not a child of the calling process.
525 An invalid value was provided for the @var{options} argument.
529 These symbolic constants are defined as values for the @var{pid} argument
530 to the @code{waitpid} function.
532 @comment Extra blank lines make it look better.
536 This constant macro (whose value is @code{-1}) specifies that
537 @code{waitpid} should return status information about any child process.
541 This constant (with value @code{0}) specifies that @code{waitpid} should
542 return status information about any child process in the same process
543 group as the calling process.
546 These symbolic constants are defined as flags for the @var{options}
547 argument to the @code{waitpid} function. You can bitwise-OR the flags
548 together to obtain a value to use as the argument.
553 This flag specifies that @code{waitpid} should return immediately
554 instead of waiting, if there is no child process ready to be noticed.
558 This flag specifies that @code{waitpid} should report the status of any
559 child processes that have been stopped as well as those that have
565 @deftypefun pid_t wait (int *@var{status-ptr})
566 This is a simplified version of @code{waitpid}, and is used to wait
567 until any one child process terminates. The call:
574 is exactly equivalent to:
577 waitpid (-1, &status, 0)
580 This function is a cancelation point in multi-threaded programs. This
581 is a problem if the thread allocates some resources (like memory, file
582 descriptors, semaphores or whatever) at the time @code{wait} is
583 called. If the thread gets canceled these resources stay allocated
584 until the program ends. To avoid this calls to @code{wait} should be
585 protected using cancelation handlers.
586 @c ref pthread_cleanup_push / pthread_cleanup_pop
591 @deftypefun pid_t wait4 (pid_t @var{pid}, int *@var{status-ptr}, int @var{options}, struct rusage *@var{usage})
592 If @var{usage} is a null pointer, @code{wait4} is equivalent to
593 @code{waitpid (@var{pid}, @var{status-ptr}, @var{options})}.
595 If @var{usage} is not null, @code{wait4} stores usage figures for the
596 child process in @code{*@var{rusage}} (but only if the child has
597 terminated, not if it has stopped). @xref{Resource Usage}.
599 This function is a BSD extension.
602 Here's an example of how to use @code{waitpid} to get the status from
603 all child processes that have terminated, without ever waiting. This
604 function is designed to be a handler for @code{SIGCHLD}, the signal that
605 indicates that at least one child process has terminated.
610 sigchld_handler (int signum)
612 int pid, status, serrno;
616 pid = waitpid (WAIT_ANY, &status, WNOHANG);
624 notice_termination (pid, status);
631 @node Process Completion Status
632 @section Process Completion Status
634 If the exit status value (@pxref{Program Termination}) of the child
635 process is zero, then the status value reported by @code{waitpid} or
636 @code{wait} is also zero. You can test for other kinds of information
637 encoded in the returned status value using the following macros.
638 These macros are defined in the header file @file{sys/wait.h}.
643 @deftypefn Macro int WIFEXITED (int @var{status})
644 This macro returns a nonzero value if the child process terminated
645 normally with @code{exit} or @code{_exit}.
650 @deftypefn Macro int WEXITSTATUS (int @var{status})
651 If @code{WIFEXITED} is true of @var{status}, this macro returns the
652 low-order 8 bits of the exit status value from the child process.
658 @deftypefn Macro int WIFSIGNALED (int @var{status})
659 This macro returns a nonzero value if the child process terminated
660 because it received a signal that was not handled.
661 @xref{Signal Handling}.
666 @deftypefn Macro int WTERMSIG (int @var{status})
667 If @code{WIFSIGNALED} is true of @var{status}, this macro returns the
668 signal number of the signal that terminated the child process.
673 @deftypefn Macro int WCOREDUMP (int @var{status})
674 This macro returns a nonzero value if the child process terminated
675 and produced a core dump.
680 @deftypefn Macro int WIFSTOPPED (int @var{status})
681 This macro returns a nonzero value if the child process is stopped.
686 @deftypefn Macro int WSTOPSIG (int @var{status})
687 If @code{WIFSTOPPED} is true of @var{status}, this macro returns the
688 signal number of the signal that caused the child process to stop.
692 @node BSD Wait Functions
693 @section BSD Process Wait Functions
695 The GNU library also provides these related facilities for compatibility
696 with BSD Unix. BSD uses the @code{union wait} data type to represent
697 status values rather than an @code{int}. The two representations are
698 actually interchangeable; they describe the same bit patterns. The GNU
699 C Library defines macros such as @code{WEXITSTATUS} so that they will
700 work on either kind of object, and the @code{wait} function is defined
701 to accept either type of pointer as its @var{status-ptr} argument.
703 These functions are declared in @file{sys/wait.h}.
708 @deftp {Data Type} {union wait}
709 This data type represents program termination status values. It has
710 the following members:
714 The value of this member is the same as that of the
715 @code{WTERMSIG} macro.
718 The value of this member is the same as that of the
719 @code{WCOREDUMP} macro.
722 The value of this member is the same as that of the
723 @code{WEXITSTATUS} macro.
726 The value of this member is the same as that of the
727 @code{WSTOPSIG} macro.
730 Instead of accessing these members directly, you should use the
734 The @code{wait3} function is the predecessor to @code{wait4}, which is
735 more flexible. @code{wait3} is now obsolete.
739 @deftypefun pid_t wait3 (union wait *@var{status-ptr}, int @var{options}, struct rusage *@var{usage})
740 If @var{usage} is a null pointer, @code{wait3} is equivalent to
741 @code{waitpid (-1, @var{status-ptr}, @var{options})}.
743 If @var{usage} is not null, @code{wait3} stores usage figures for the
744 child process in @code{*@var{rusage}} (but only if the child has
745 terminated, not if it has stopped). @xref{Resource Usage}.
748 @node Process Creation Example
749 @section Process Creation Example
751 Here is an example program showing how you might write a function
752 similar to the built-in @code{system}. It executes its @var{command}
753 argument using the equivalent of @samp{sh -c @var{command}}.
759 #include <sys/types.h>
760 #include <sys/wait.h>
762 /* @r{Execute the command using this shell program.} */
763 #define SHELL "/bin/sh"
767 my_system (const char *command)
776 /* @r{This is the child process. Execute the shell command.} */
777 execl (SHELL, SHELL, "-c", command, NULL);
778 _exit (EXIT_FAILURE);
781 /* @r{The fork failed. Report failure.} */
784 /* @r{This is the parent process. Wait for the child to complete.} */
785 if (waitpid (pid, &status, 0) != pid)
791 @comment Yes, this example has been tested.
793 There are a couple of things you should pay attention to in this
796 Remember that the first @code{argv} argument supplied to the program
797 represents the name of the program being executed. That is why, in the
798 call to @code{execl}, @code{SHELL} is supplied once to name the program
799 to execute and a second time to supply a value for @code{argv[0]}.
801 The @code{execl} call in the child process doesn't return if it is
802 successful. If it fails, you must do something to make the child
803 process terminate. Just returning a bad status code with @code{return}
804 would leave two processes running the original program. Instead, the
805 right behavior is for the child process to report failure to its parent
808 Call @code{_exit} to accomplish this. The reason for using @code{_exit}
809 instead of @code{exit} is to avoid flushing fully buffered streams such
810 as @code{stdout}. The buffers of these streams probably contain data
811 that was copied from the parent process by the @code{fork}, data that
812 will be output eventually by the parent process. Calling @code{exit} in
813 the child would output the data twice. @xref{Termination Internals}.