@Go to the ‰ŠP�”›first@�”˜, ‰ŠP�”›previous@�”˜, ‰ŠP�”›next@�”˜, ‰ŠP�”›last@�”˜ section, ‰ŠP�”›table of contents@�”˜.
Œ

ˆ‰SEC407Št�”›Processes

‰IDX1855ŠB�”˜Processes@ are the primitive units for allocation of system resources. Each process has its own address space and (usually) one thread of control. A process executes a program; you can have multiple processes executing the same program, but each process has its own copy of the program within its own address space and executes it independently of the other copies.
‰IDX1856Š‰IDX1857Š@�”˜Processes are organized hierarchically. Each process has a Bparent process@ which explicitly arranged to create it. The processes created by a given parent are called its Bchild processes@. A child inherits many of its attributes from the parent process.
This chapter describes how a program can create, terminate, and control child processes. Actually, there are three distinct operations involved: creating a new child process, causing the new process to execute a program, and coordinating the completion of the child process with the original program.
The Hsystem@ function provides a simple, portable mechanism for running another program; it does all three steps automatically. If you need more control over the details of how this is done, you can use the primitive functions to do each step individually instead.
ˆ‰SEC408Št�”›Running a Command

‰IDX1858Š
@�”˜The easy way to run another program is to use the Hsystem@ function. This function does all the work of running a subprogram, but it doesn't give you much control over the details: you have to wait until the subprogram terminates before you can do anything else.

AFunction:@ int Dsystem@ B(const char *Bcommand@)
Â‰IDX1859Š‰IDX1860Š@�”˜This function executes Bcommand@ as a shell command. In the GNU C library, it always uses the default shell Hsh@ to run the command. In particular, it searches the directories in HPATH@ to find programs to execute. The return value is H-1@ if it wasn't possible to create the shell process, and otherwise is the status of the shell process. See section ‰ŠP�”›Process Completion@�”˜, for details on how this status code can be interpreted.
‰IDX1861Š@�”˜The Hsystem@ function is declared in the header file H`stdlib.h'@.À

DPortability Note:@ Some C implementations may not have any notion of a command processor that can execute other programs. You can determine whether a command processor exists by executing Hsystem (NULL)@; if the return value is nonzero, a command processor is available.
The Hpopen@ and Hpclose@ functions (see section ‰ŠP�”›Pipe to a Subprocess@�”˜) are closely related to the Hsystem@ function. They allow the parent process to communicate with the standard input and output channels of the command being executed.
ˆ‰SEC409Št�”›Process Creation Concepts

@�”˜This section gives an overview of processes and of the steps involved in creating a process and making it run another program.
‰IDX1862Š‰IDX1863Š@�”˜Each process is named by a Bprocess ID@ number. A unique process ID is allocated to each process when it is created. The Blifetime@ of a process ends when its termination is reported to its parent process; at that time, all of the process resources, including its process ID, are freed.
‰IDX1864Š‰IDX1865Š‰IDX1866Š‰IDX1867Š@�”˜Processes are created with the Hfork@ system call (so the operation of creating a new process is sometimes called Bforking@ a process). The Bchild process@ created by Hfork@ is a copy of the original Bparent process@, except that it has its own process ID.
After forking a child process, both the parent and child processes continue to execute normally. If you want your program to wait for a child process to finish executing before continuing, you must do this explicitly after the fork operation, by calling Hwait@ or Hwaitpid@ (see section ‰ŠP�”›Process Completion@�”˜). These functions give you limited information about why the child terminated--for example, its exit status code.
A newly forked child process continues to execute the same program as its parent process, at the point where the Hfork@ call returns. You can use the return value from Hfork@ to tell whether the program is running in the parent process or the child.
‰IDX1868Š@�”˜Having several processes run the same program is only occasionally useful. But the child can execute another program using one of the Hexec@ functions; see section ‰ŠP�”›Executing a File@�”˜. The program that the process is executing is called its Bprocess image@. Starting execution of a new program causes the process to forget all about its previous process image; when the new program exits, the process exits too, instead of returning to the previous process image.
ˆ‰SEC410Št�”›Process Identification

@�”˜The Hpid_t@ data type represents process IDs. You can get the process ID of a process by calling Hgetpid@. The function Hgetppid@ returns the process ID of the parent of the current process (this is also known as the Bparent process ID@). Your program should include the header files H`unistd.h'@ and H`sys/types.h'@ to use these functions. ‰IDX1869Š‰IDX1870Š

A�”˜Data Type:@ Dpid_t
Â‰IDX1871Š@�”˜The Hpid_t@ data type is a signed integer type which is capable of representing a process ID. In the GNU library, this is an Hint@.À

AFunction:@ pid_t Dgetpid@ B(void)
Â‰IDX1872Š@�”˜The Hgetpid@ function returns the process ID of the current process.À

AFunction:@ pid_t Dgetppid@ B(void)
Â‰IDX1873Š@�”˜The Hgetppid@ function returns the process ID of the parent of the current process.À

ˆ‰SEC411Št�”›Creating a Process

@�”˜The Hfork@ function is the primitive for creating a process. It is declared in the header file H`unistd.h'@. ‰IDX1874Š

A�”˜Function:@ pid_t Dfork@ B(void)
Â‰IDX1875Š@�”˜The Hfork@ function creates a new process.
If the operation is successful, there are then both parent and child processes and both see Hfork@ return, but with different values: it returns a value of H0@ in the child process and returns the child's process ID in the parent process.
If process creation failed, Hfork@ returns a value of H-1@ in the parent process. The following Herrno@ error conditions are defined for Hfork@:
HEAGAIN
Ä@There aren't enough system resources to create another process, or the user already has too many processes running. This means exceeding the HRLIMIT_NPROC@ resource limit, which can usually be increased; see section ‰ŠP�”›Limiting Resource Usage@�”˜.
ÂHENOMEM
Ä@The process requires more space than the system can supply.Â
À

The specific attributes of the child process that differ from the parent process are: þÂ
• The child process has its own unique process ID.
• The parent process ID of the child process is the process ID of its parent process.
• The child process gets its own copies of the parent process's open file descriptors. Subsequently changing attributes of the file descriptors in the parent process won't affect the file descriptors in the child, and vice versa. See section ‰ŠP�”›Control Operations on Files@�”˜. However, the file position associated with each descriptor is shared by both processes; see section ‰ŠP�”›File Position@�”˜.
• The elapsed processor times for the child process are set to zero; see section ‰ŠP�”›Processor Time@�”˜.
• The child doesn't inherit file locks set by the parent process. See section ‰ŠP�”›Control Operations on Files@�”˜.
• The child doesn't inherit alarms set by the parent process. See section ‰ŠP�”›Setting an Alarm@�”˜.
• The set of pending signals (see section ‰ŠP�”›How Signals Are Delivered@�”˜) for the child process is cleared. (The child process inherits its mask of blocked signals and signal actions from the parent process.)Àð

AFunction:@ pid_t Dvfork@ B(void)
Â‰IDX1876Š@�”˜The Hvfork@ function is similar to Hfork@ but on systems it is more efficient; however, there are restrictions you must follow to use it safely.
While Hfork@ makes a complete copy of the calling process's address space and allows both the parent and child to execute independently, Hvfork@ does not make this copy. Instead, the child process created with Hvfork@ shares its parent's address space until it calls exits or one of the Hexec@ functions. In the meantime, the parent process suspends execution.
You must be very careful not to allow the child process created with Hvfork@ to modify any global data or even local variables shared with the parent. Furthermore, the child process cannot return from (or do a long jump out of) the function that called Hvfork@! This would leave the parent process's control information very confused. If in doubt, use Hfork@ instead.
Some operating systems don't really implement Hvfork@. The GNU C library permits you to use Hvfork@ on all systems, but actually executes Hfork@ if Hvfork@ isn't available. If you follow the proper precautions for using Hvfork@, your program will still work even if the system uses Hfork@ instead.À

ˆ‰SEC412Št�”›Executing a File

‰IDX1877Š‰IDX1878Š
@�”˜This section describes the Hexec@ family of functions, for executing a file as a process image. You can use these functions to make a child process execute a new program after it has been forked.
‰IDX1879Š@�”˜The functions in this family differ in how you specify the arguments, but otherwise they all do the same thing. They are declared in the header file H`unistd.h'@.

AFunction:@ int Dexecv@ B(const char *Bfilename@, char *const BargvH[]@)
Â‰IDX1880Š@�”˜The Hexecv@ function executes the file named by Bfilename@ as a new process image.
The Bargv@ argument is an array of null-terminated strings that is used to provide a value for the Hargv@ argument to the Hmain@ function of the program to be executed. The last element of this array must be a null pointer. By convention, the first element of this array is the file name of the program sans directory names. See section ‰ŠP�”›Program Arguments@�”˜, for full details on how programs can access these arguments.
The environment for the new process image is taken from the Henviron@ variable of the current process image; see section ‰ŠP�”›Environment Variables@�”˜, for information about environments.À

AFunction:@ int Dexecl@ B(const char *Bfilename@, const char *Barg0@, ...)
Â‰IDX1881Š@�”˜This is similar to Hexecv@, but the Bargv@ strings are specified individually instead of as an array. A null pointer must be passed as the last such argument.À

AFunction:@ int Dexecve@ B(const char *Bfilename@, char *const BargvH[]@, char *const BenvH[]@)
Â‰IDX1882Š@�”˜This is similar to Hexecv@, but permits you to specify the environment for the new program explicitly as the Benv@ argument. This should be an array of strings in the same format as for the Henviron@ variable; see section ‰ŠP�”›Environment Access@�”˜.À

AFunction:@ int Dexecle@ B(const char *Bfilename@, const char *Barg0@, char *const BenvH[]@, ...)
Â‰IDX1883Š@�”˜This is similar to Hexecl@, but permits you to specify the environment for the new program explicitly. The environment argument is passed following the null pointer that marks the last Bargv@ argument, and should be an array of strings in the same format as for the Henviron@ variable.À

AFunction:@ int Dexecvp@ B(const char *Bfilename@, char *const BargvH[]@)
Â‰IDX1884Š@�”˜The Hexecvp@ function is similar to Hexecv@, except that it searches the directories listed in the HPATH@ environment variable (see section ‰ŠP�”›Standard Environment Variables@�”˜) to find the full file name of a file from Bfilename@ if Bfilename@ does not contain a slash.
This function is useful for executing system utility programs, because it looks for them in the places that the user has chosen. Shells use it to run the commands that users type.À

AFunction:@ int Dexeclp@ B(const char *Bfilename@, const char *Barg0@, ...)
Â‰IDX1885Š@�”˜This function is like Hexecl@, except that it performs the same file name searching as the Hexecvp@ function.À

The size of the argument list and environment list taken together must not be greater than HARG_MAX@ bytes. See section ‰ŠP�”›General Capacity Limits@�”˜. In the GNU system, the size (which compares against HARG_MAX@) includes, for each string, the number of characters in the string, plus the size of a Hchar *@, plus one, rounded up to a multiple of the size of a Hchar *@. Other systems may have somewhat different rules for counting.
These functions normally don't return, since execution of a new program causes the currently executing program to go away completely. A value of H-1@ is returned in the event of a failure. In addition to the usual file name errors (see section ‰ŠP�”›File Name Errors@�”˜), the following Herrno@ error conditions are defined for these functions:
HE2BIG
Â@The combined size of the new program's argument list and environment list is larger than HARG_MAX@ bytes. The GNU system has no specific limit on the argument list size, so this error code cannot result, but you may get HENOMEM@ instead if the arguments are too big for available memory.
ÀHENOEXEC
Â@The specified file can't be executed because it isn't in the right format.
ÀHENOMEM
Â@Executing the specified file requires more storage than is available.À

If execution of the new file succeeds, it updates the access time field of the file as if the file had been read. See section ‰ŠP�”›File Times@�”˜, for more details about access times of files.
The point at which the file is closed again is not specified, but is at some point before the process exits or before another process image is executed.
Executing a new process image completely changes the contents of memory, copying only the argument and environment strings to new locations. But many other attributes of the process are unchanged: þÂ
• The process ID and the parent process ID. See section ‰ŠP�”›Process Creation Concepts@�”˜.
• Session and process group membership. See section ‰ŠP�”›Concepts of Job Control@�”˜.
• Real user ID and group ID, and supplementary group IDs. See section ‰ŠP�”›The Persona of a Process@�”˜.
• Pending alarms. See section ‰ŠP�”›Setting an Alarm@�”˜.
• Current working directory and root directory. See section ‰ŠP�”›Working Directory@�”˜. In the GNU system, the root directory is not copied when executing a setuid program; instead the system default root directory is used for the new program.
• File mode creation mask. See section ‰ŠP�”›Assigning File Permissions@�”˜.
• Process signal mask; see section ‰ŠP�”›Process Signal Mask@�”˜.
• Pending signals; see section ‰ŠP�”›Blocking Signals@�”˜.
• Elapsed processor time associated with the process; see section ‰ŠP�”›Processor Time@�”˜.Àð
If the set-user-ID and set-group-ID mode bits of the process image file are set, this affects the effective user ID and effective group ID (respectively) of the process. These concepts are discussed in detail in section ‰ŠP�”›The Persona of a Process@�”˜.
Signals that are set to be ignored in the existing process image are also set to be ignored in the new process image. All other signals are set to the default action in the new process image. For more information about signals, see section ‰ŠP�”›Signal Handling@�”˜.
File descriptors open in the existing process image remain open in the new process image, unless they have the HFD_CLOEXEC@ (close-on-exec) flag set. The files that remain open inherit all attributes of the open file description from the existing process image, including file locks. File descriptors are discussed in section ‰ŠP�”›Low-Level Input/Output@�”˜.
Streams, by contrast, cannot survive through Hexec@ functions, because they are located in the memory of the process itself. The new process image has no streams except those it creates afresh. Each of the streams in the pre-Hexec@ process image has a descriptor inside it, and these descriptors do survive through Hexec@ (provided that they do not have HFD_CLOEXEC@ set). The new process image can reconnect these to new streams using Hfdopen@ (see section ‰ŠP�”›Descriptors and Streams@�”˜).
ˆ‰SEC413Št�”›Process Completion

‰IDX1886Š‰IDX1887Š‰IDX1888Š
@�”˜The functions described in this section are used to wait for a child process to terminate or stop, and determine its status. These functions are declared in the header file H`sys/wait.h'@. ‰IDX1889Š

A�”˜Function:@ pid_t Dwaitpid@ B(pid_t Bpid@, int *Bstatus-ptr@, int Boptions@)
Â‰IDX1890Š@�”˜The Hwaitpid@ function is used to request status information from a child process whose process ID is Bpid@. Normally, the calling process is suspended until the child process makes status information available by terminating.
Other values for the Bpid@ argument have special interpretations. A value of H-1@ or HWAIT_ANY@ requests status information for any child process; a value of H0@ or HWAIT_MYPGRP@ requests information for any child process in the same process group as the calling process; and any other negative value - Bpgid@ requests information for any child process whose process group ID is Bpgid@.
If status information for a child process is available immediately, this function returns immediately without waiting. If more than one eligible child process has status information available, one of them is chosen randomly, and its status is returned immediately. To get the status from the other eligible child processes, you need to call Hwaitpid@ again.
The Boptions@ argument is a bit mask. Its value should be the bitwise OR (that is, the H`|'@ operator) of zero or more of the HWNOHANG@ and HWUNTRACED@ flags. You can use the HWNOHANG@ flag to indicate that the parent process shouldn't wait; and the HWUNTRACED@ flag to request status information from stopped processes as well as processes that have terminated.
The status information from the child process is stored in the object that Bstatus-ptr@ points to, unless Bstatus-ptr@ is a null pointer.
The return value is normally the process ID of the child process whose status is reported. If the HWNOHANG@ option was specified and no child process is waiting to be noticed, the value is zero. A value of H-1@ is returned in case of error. The following Herrno@ error conditions are defined for this function:
HEINTR
Ä@The function was interrupted by delivery of a signal to the calling process. See section ‰ŠP�”›Primitives Interrupted by Signals@�”˜.
ÂHECHILD
Ä@There are no child processes to wait for, or the specified Bpid@ is not a child of the calling process.
ÂHEINVAL
Ä@An invalid value was provided for the Boptions@ argument.Â
À

These symbolic constants are defined as values for the Bpid@ argument to the Hwaitpid@ function.
HWAIT_ANY
Â@This constant macro (whose value is H-1@) specifies that Hwaitpid@ should return status information about any child process.
ÀHWAIT_MYPGRP
Â@This constant (with value H0@) specifies that Hwaitpid@ should return status information about any child process in the same process group as the calling process.À

These symbolic constants are defined as flags for the Boptions@ argument to the Hwaitpid@ function. You can bitwise-OR the flags together to obtain a value to use as the argument.
HWNOHANG
Â@This flag specifies that Hwaitpid@ should return immediately instead of waiting, if there is no child process ready to be noticed.
ÀHWUNTRACED
Â@This flag specifies that Hwaitpid@ should report the status of any child processes that have been stopped as well as those that have terminated.À

AFunction:@ pid_t Dwait@ B(int *Bstatus-ptr@)
Â‰IDX1891Š@�”˜This is a simplified version of Hwaitpid@, and is used to wait until any one child process terminates. The call: wait (&status)
is exactly equivalent to: waitpid (-1, &status, 0) À

AFunction:@ pid_t Dwait4@ B(pid_t Bpid@, int *Bstatus-ptr@, int Boptions@, struct rusage *Busage@)
Â‰IDX1892Š@�”˜If Busage@ is a null pointer, Hwait4@ is equivalent to Hwaitpid (JpidH, Jstatus-ptrH, JoptionsH)@.
If Busage@ is not null, Hwait4@ stores usage figures for the child process in H*Jrusage@ (but only if the child has terminated, not if it has stopped). See section ‰ŠP�”›Resource Usage@�”˜.
This function is a BSD extension.À

Here's an example of how to use Hwaitpid@ to get the status from all child processes that have terminated, without ever waiting. This function is designed to be a handler for HSIGCHLD@, the signal that indicates that at least one child process has terminated. void
sigchld_handler (int signum)
{
int pid;
int status;
while (1)
{
pid = waitpid (WAIT_ANY, &status, WNOHANG);
if (pid < 0)
{
perror ("waitpid");
break;
}
if (pid == 0)
break;
notice_termination (pid, status);
}
}
ˆ‰SEC414Št�”›Process Completion Status

@�”˜If the exit status value (see section ‰ŠP�”›Program Termination@�”˜) of the child process is zero, then the status value reported by Hwaitpid@ or Hwait@ is also zero. You can test for other kinds of information encoded in the returned status value using the following macros. These macros are defined in the header file H`sys/wait.h'@. ‰IDX1893Š

A�”˜Macro:@ int DWIFEXITED@ B(int Bstatus@)
Â‰IDX1894Š@�”˜This macro returns a nonzero value if the child process terminated normally with Hexit@ or H_exit@.À

AMacro:@ int DWEXITSTATUS@ B(int Bstatus@)
Â‰IDX1895Š@�”˜If HWIFEXITED@ is true of Bstatus@, this macro returns the low-order 8 bits of the exit status value from the child process. See section ‰ŠP�”›Exit Status@�”˜.À

AMacro:@ int DWIFSIGNALED@ B(int Bstatus@)
Â‰IDX1896Š@�”˜This macro returns a nonzero value if the child process terminated because it received a signal that was not handled. See section ‰ŠP�”›Signal Handling@�”˜.À

AMacro:@ int DWTERMSIG@ B(int Bstatus@)
Â‰IDX1897Š@�”˜If HWIFSIGNALED@ is true of Bstatus@, this macro returns the signal number of the signal that terminated the child process.À

AMacro:@ int DWCOREDUMP@ B(int Bstatus@)
Â‰IDX1898Š@�”˜This macro returns a nonzero value if the child process terminated and produced a core dump.À

AMacro:@ int DWIFSTOPPED@ B(int Bstatus@)
Â‰IDX1899Š@�”˜This macro returns a nonzero value if the child process is stopped.À

AMacro:@ int DWSTOPSIG@ B(int Bstatus@)
Â‰IDX1900Š@�”˜If HWIFSTOPPED@ is true of Bstatus@, this macro returns the signal number of the signal that caused the child process to stop.À

ˆ‰SEC415Št�”›BSD Process Wait Functions

@�”˜The GNU library also provides these related facilities for compatibility with BSD Unix. BSD uses the Hunion wait@ data type to represent status values rather than an Hint@. The two representations are actually interchangeable; they describe the same bit patterns. The GNU C Library defines macros such as HWEXITSTATUS@ so that they will work on either kind of object, and the Hwait@ function is defined to accept either type of pointer as its Bstatus-ptr@ argument.
These functions are declared in H`sys/wait.h'@. ‰IDX1901Š

A�”˜Data Type:@ Dunion wait
Â‰IDX1902Š@�”˜This data type represents program termination status values. It has the following members:
Hint w_termsig
Ä@The value of this member is the same as the result of the HWTERMSIG@ macro.
ÂHint w_coredump
Ä@The value of this member is the same as the result of the HWCOREDUMP@ macro.
ÂHint w_retcode
Ä@The value of this member is the same as the result of the HWEXITSTATUS@ macro.
ÂHint w_stopsig
Ä@The value of this member is the same as the result of the HWSTOPSIG@ macro.Â

Instead of accessing these members directly, you should use the equivalent macros.À

The Hwait3@ function is the predecessor to Hwait4@, which is more flexible. Hwait3@ is now obsolete.

AFunction:@ pid_t Dwait3@ B(union wait *Bstatus-ptr@, int Boptions@, struct rusage *Busage@)
Â‰IDX1903Š@�”˜If Busage@ is a null pointer, Hwait3@ is equivalent to Hwaitpid (-1, Jstatus-ptrH, JoptionsH)@.
If Busage@ is not null, Hwait3@ stores usage figures for the child process in H*Jrusage@ (but only if the child has terminated, not if it has stopped). See section ‰ŠP�”›Resource Usage@�”˜.À

ˆ‰SEC416Št�”›Process Creation Example

@�”˜Here is an example program showing how you might write a function similar to the built-in Hsystem@. It executes its Bcommand@ argument using the equivalent of H`sh -c JcommandH'@. #include <stddef.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

/* Execute the command using this shell program. */
#define SHELL "/bin/sh"

int
my_system (const char *command)
{
int status;
pid_t pid;

pid = fork ();
if (pid == 0)
{
/* This is the child process. Execute the shell command. */
execl (SHELL, SHELL, "-c", command, NULL);
_exit (EXIT_FAILURE);
}
else if (pid < 0)
/* The fork failed. Report failure. */
status = -1;
else
/* This is the parent process. Wait for the child to complete. */
if (waitpid (pid, &status, 0) != pid)
status = -1;
return status;
}
There are a couple of things you should pay attention to in this example.
Remember that the first Hargv@ argument supplied to the program represents the name of the program being executed. That is why, in the call to Hexecl@, HSHELL@ is supplied once to name the program to execute and a second time to supply a value for Hargv[0]@.
The Hexecl@ call in the child process doesn't return if it is successful. If it fails, you must do something to make the child process terminate. Just returning a bad status code with Hreturn@ would leave two processes running the original program. Instead, the right behavior is for the child process to report failure to its parent process.
Call H_exit@ to accomplish this. The reason for using H_exit@ instead of Hexit@ is to avoid flushing fully buffered streams such as Hstdout@. The buffers of these streams probably contain data that was copied from the parent process by the Hfork@, data that will be output eventually by the parent process. Calling Hexit@ in the child would output the data twice. See section ‰ŠP�”›Termination Internals@�”˜.
Œ
Go to the ‰ŠP�”›first@�”˜, ‰ŠP�”›previous@�”˜, ‰ŠP�”›next@�”˜, ‰ŠP�”›last@�”˜ section, ‰ŠP�”›table of contents@�”˜.