1FORK(P)                    POSIX Programmer's Manual                   FORK(P)
2
3
4

NAME

6       fork - create a new process
7

SYNOPSIS

9       #include <unistd.h>
10
11       pid_t fork(void);
12
13

DESCRIPTION

15       The  fork() function shall create a new process. The new process (child
16       process) shall be an exact copy of the calling process (parent process)
17       except as detailed below:
18
19        * The child process shall have a unique process ID.
20
21        * The  child  process ID also shall not match any active process group
22          ID.
23
24        * The child process shall have a different parent  process  ID,  which
25          shall be the process ID of the calling process.
26
27        * The  child  process  shall  have  its  own copy of the parent's file
28          descriptors.  Each of the child's file descriptors  shall  refer  to
29          the  same open file description with the corresponding file descrip‐
30          tor of the parent.
31
32        * The child process shall have its  own  copy  of  the  parent's  open
33          directory  streams.  Each open directory stream in the child process
34          may share directory stream positioning with the corresponding direc‐
35          tory stream of the parent.
36
37        * The  child  process  shall have its own copy of the parent's message
38          catalog descriptors.
39
40        * The child process' values of tms_utime, tms_stime,  tms_cutime,  and
41          tms_cstime shall be set to 0.
42
43        * The  time  left  until an alarm clock signal shall be reset to zero,
44          and the alarm, if any, shall be canceled; see alarm() .
45
46        * All semadj values shall be cleared.
47
48        * File locks set by the parent process shall not be inherited  by  the
49          child process.
50
51        * The  set  of signals pending for the child process shall be initial‐
52          ized to the empty set.
53
54        * Interval timers shall be reset in the child process.
55
56        * Any semaphores that are open in the parent  process  shall  also  be
57          open in the child process.
58
59        * The  child  process shall not inherit any address space memory locks
60          established by  the  parent  process  via  calls  to  mlockall()  or
61          mlock().
62
63        * Memory mappings created in the parent shall be retained in the child
64          process. MAP_PRIVATE mappings inherited from the parent  shall  also
65          be  MAP_PRIVATE  mappings in the child, and any modifications to the
66          data in these mappings made by the parent prior  to  calling  fork()
67          shall  be  visible  to  the  child. Any modifications to the data in
68          MAP_PRIVATE mappings made by the parent after fork()  returns  shall
69          be visible only to the parent. Modifications to the data in MAP_PRI‐
70          VATE mappings made by the child shall be visible only to the child.
71
72        * For the SCHED_FIFO  and  SCHED_RR  scheduling  policies,  the  child
73          process shall inherit the policy and priority settings of the parent
74          process during a fork() function. For other scheduling policies, the
75          policy and priority settings on fork() are implementation-defined.
76
77        * Per-process  timers  created by the parent shall not be inherited by
78          the child process.
79
80        * The child process shall have its  own  copy  of  the  message  queue
81          descriptors  of  the  parent. Each of the message descriptors of the
82          child shall refer to the same open message queue description as  the
83          corresponding message descriptor of the parent.
84
85        * No  asynchronous  input  or  asynchronous output operations shall be
86          inherited by the child process.
87
88        * A process shall be created with a single thread. If a multi-threaded
89          process calls fork(), the new process shall contain a replica of the
90          calling thread and its entire address space, possibly including  the
91          states  of  mutexes  and  other  resources.   Consequently, to avoid
92          errors, the child process may only execute async-signal-safe  opera‐
93          tions  until  such  time  as  one  of  the exec functions is called.
94           Fork handlers may be established by means of  the  pthread_atfork()
95          function  in  order to maintain application invariants across fork()
96          calls.
97
98       When the application calls fork() from a signal handler and any of  the
99       fork  handlers  registered by pthread_atfork() calls a function that is
100       not asynch-signal-safe, the behavior is undefined.
101
102        * If the Trace option and the Trace Inherit option are both supported:
103
104       If the calling process was being traced in a trace stream that had  its
105       inheritance  policy  set  to  POSIX_TRACE_INHERITED,  the child process
106       shall be traced into that trace stream, and  the  child  process  shall
107       inherit  the  parent's mapping of trace event names to trace event type
108       identifiers. If the trace stream in which the calling process was being
109       traced  had  its inheritance policy set to POSIX_TRACE_CLOSE_FOR_CHILD,
110       the child process shall not be  traced  into  that  trace  stream.  The
111       inheritance  policy  is set by a call to the posix_trace_attr_setinher‐
112       ited() function.
113
114        * If the Trace option is supported, but the Trace  Inherit  option  is
115          not supported:
116
117       The  child process shall not be traced into any of the trace streams of
118       its parent process.
119
120        * If the Trace option is supported, the child process of a trace  con‐
121          troller  process  shall  not control the trace streams controlled by
122          its parent process.
123
124        * The initial value of the CPU-time clock of the child  process  shall
125          be set to zero.
126
127        * The  initial value of the CPU-time clock of the single thread of the
128          child process shall be set to zero.
129
130       All other process characteristics defined by IEEE Std 1003.1-2001 shall
131       be  the  same  in  the  parent and child processes.  The inheritance of
132       process characteristics not defined by IEEE Std 1003.1-2001 is unspeci‐
133       fied by IEEE Std 1003.1-2001.
134
135       After  fork(), both the parent and the child processes shall be capable
136       of executing independently before either one terminates.
137

RETURN VALUE

139       Upon successful completion, fork() shall return 0 to the child  process
140       and  shall  return  the  process  ID of the child process to the parent
141       process. Both processes shall continue to execute from the fork() func‐
142       tion.  Otherwise,  -1 shall be returned to the parent process, no child
143       process shall be created, and errno shall be set to indicate the error.
144

ERRORS

146       The fork() function shall fail if:
147
148       EAGAIN The system lacked the  necessary  resources  to  create  another
149              process, or the system-imposed limit on the total number of pro‐
150              cesses  under  execution  system-wide  or  by  a   single   user
151              {CHILD_MAX} would be exceeded.
152
153
154       The fork() function may fail if:
155
156       ENOMEM Insufficient storage space is available.
157
158
159       The following sections are informative.
160

EXAMPLES

162       None.
163

APPLICATION USAGE

165       None.
166

RATIONALE

168       Many historical implementations have timing windows where a signal sent
169       to a process group (for example, an interactive SIGINT) just  prior  to
170       or  during execution of fork() is delivered to the parent following the
171       fork() but not to the child because the fork() code clears the  child's
172       set  of  pending signals.  This volume of IEEE Std 1003.1-2001 does not
173       require, or even permit, this behavior. However,  it  is  pragmatic  to
174       expect  that problems of this nature may continue to exist in implemen‐
175       tations that appear to conform to this volume  of  IEEE Std 1003.1-2001
176       and pass available verification suites.  This behavior is only a conse‐
177       quence of the implementation failing to make the interval between  sig‐
178       nal  generation  and delivery totally invisible. From the application's
179       perspective, a fork() call should appear atomic. A signal that is  gen‐
180       erated  prior to the fork() should be delivered prior to the fork().  A
181       signal sent to the process group after the fork() should  be  delivered
182       to  both  parent  and child. The implementation may actually initialize
183       internal data structures corresponding to the child's  set  of  pending
184       signals to include signals sent to the process group during the fork().
185       Since the fork() call can be considered as  atomic  from  the  applica‐
186       tion's perspective, the set would be initialized as empty and such sig‐
187       nals would have arrived after the fork(); see also <signal.h>.
188
189       One approach that has been suggested to address the problem  of  signal
190       inheritance  across  fork()  is to add an [EINTR] error, which would be
191       returned when a signal is detected  during  the  call.  While  this  is
192       preferable  to  losing  signals, it was not considered an optimal solu‐
193       tion. Although it is not recommended for this purpose,  such  an  error
194       would be an allowable extension for an implementation.
195
196       The  [ENOMEM]  error  value  is reserved for those implementations that
197       detect and distinguish such a condition. This condition occurs when  an
198       implementation  detects  that  there is not enough memory to create the
199       process. This is intended to be returned when [EAGAIN] is inappropriate
200       because  there  can never be enough memory (either primary or secondary
201       storage) to perform the operation.  Since fork() duplicates an existing
202       process,  this must be a condition where there is sufficient memory for
203       one such process, but not  for  two.  Many  historical  implementations
204       actually  return  [ENOMEM] due to temporary lack of memory, a case that
205       is not generally distinct from [EAGAIN] from the perspective of a  con‐
206       forming application.
207
208       Part of the reason for including the optional error [ENOMEM] is because
209       the SVID specifies it and it should be reserved for the error condition
210       specified  there.  The  condition is not applicable on many implementa‐
211       tions.
212
213       IEEE Std 1003.1-1988 neglected to require concurrent execution  of  the
214       parent  and child of fork(). A system that single-threads processes was
215       clearly not intended and is considered an unacceptable "toy implementa‐
216       tion" of this volume of IEEE Std 1003.1-2001. The only objection antic‐
217       ipated to the phrase "executing independently" is testability, but this
218       assertion  should  be testable. Such tests require that both the parent
219       and child can block on a detectable action of  the  other,  such  as  a
220       write  to  a  pipe or a signal. An interactive exchange of such actions
221       should be possible for the system to conform to the intent of this vol‐
222       ume of IEEE Std 1003.1-2001.
223
224       The  [EAGAIN]  error  exists to warn applications that such a condition
225       might occur. Whether it occurs or not is not  in  any  practical  sense
226       under the control of the application because the condition is usually a
227       consequence of the user's use of the system, not of  the  application's
228       code. Thus, no application can or should rely upon its occurrence under
229       any circumstances, nor should the exact semantics of  what  concept  of
230       "user"  is  used  be  of  concern to the application writer. Validation
231       writers should be cognizant of this limitation.
232
233       There are two reasons why POSIX programmers call fork(). One reason  is
234       to  create  a  new thread of control within the same program (which was
235       originally only possible in POSIX by creating a new process); the other
236       is  to  create a new process running a different program. In the latter
237       case, the call to fork() is soon followed by a call to one of the  exec
238       functions.
239
240       The  general  problem with making fork() work in a multi-threaded world
241       is what to do with all of the threads. There are two alternatives.  One
242       is  to  copy  all of the threads into the new process.  This causes the
243       programmer or implementation to deal with threads that are suspended on
244       system calls or that might be about to execute system calls that should
245       not be executed in the new process. The other alternative  is  to  copy
246       only the thread that calls fork(). This creates the difficulty that the
247       state of process-local resources is usually held in process memory.  If
248       a  thread that is not calling fork() holds a resource, that resource is
249       never released in the child process because the thread whose job it  is
250       to release the resource does not exist in the child process.
251
252       When  a  programmer  is  writing  a  multi-threaded  program, the first
253       described use of fork(), creating new threads in the same  program,  is
254       provided by the pthread_create() function.  The fork() function is thus
255       used only to run new programs, and the  effects  of  calling  functions
256       that  require certain resources between the call to fork() and the call
257       to an exec function are undefined.
258
259       The addition of the forkall() function to the standard  was  considered
260       and rejected. The forkall() function lets all the threads in the parent
261       be duplicated in the child. This essentially duplicates  the  state  of
262       the  parent  in the child. This allows threads in the child to continue
263       processing and allows locks and  the  state  to  be  preserved  without
264       explicit  pthread_atfork() code. The calling process has to ensure that
265       the threads processing state that is  shared  between  the  parent  and
266       child (that is, file descriptors or MAP_SHARED memory) behaves properly
267       after forkall(). For example, if a thread is reading a file  descriptor
268       in  the  parent  when forkall() is called, then two threads (one in the
269       parent and one in the child) are reading the file descriptor after  the
270       forkall().  If  this is not desired behavior, the parent process has to
271       synchronize with such threads before calling forkall().
272
273       While the fork() function is async-signal-safe, there is no way for  an
274       implementation  to  determine  whether the fork handlers established by
275       pthread_atfork() are async-signal-safe.  The fork handlers may  attempt
276       to  execute  portions  of the implementation that are not async-signal-
277       safe, such as those that are protected by mutexes, leading to  a  dead‐
278       lock condition. It is therefore undefined for the fork handlers to exe‐
279       cute functions that are not async-signal-safe  when  fork()  is  called
280       from a signal handler.
281
282       When  forkall() is called, threads, other than the calling thread, that
283       are in functions that can return with an [EINTR] error may  have  those
284       functions  return  [EINTR] if the implementation cannot ensure that the
285       function behaves correctly in the  parent  and  child.  In  particular,
286       pthread_cond_wait()  and  pthread_cond_timedwait()  need  to  return in
287       order to ensure that the condition has not changed. These functions can
288       be  awakened  by  a  spurious  condition  wakeup  rather than returning
289       [EINTR].
290

FUTURE DIRECTIONS

292       None.
293

SEE ALSO

295       alarm()  ,  exec()  ,  fcntl()  ,   posix_trace_attr_getinherited()   ,
296       posix_trace_trid_eventid_open() , pthread_atfork() , semop() , signal()
297       , times()  ,  the  Base  Definitions  volume  of  IEEE Std 1003.1-2001,
298       <sys/types.h>, <unistd.h>
299
301       Portions  of  this text are reprinted and reproduced in electronic form
302       from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology
303       --  Portable  Operating  System  Interface (POSIX), The Open Group Base
304       Specifications Issue 6, Copyright (C) 2001-2003  by  the  Institute  of
305       Electrical  and  Electronics  Engineers, Inc and The Open Group. In the
306       event of any discrepancy between this version and the original IEEE and
307       The  Open Group Standard, the original IEEE and The Open Group Standard
308       is the referee document. The original Standard can be  obtained  online
309       at http://www.opengroup.org/unix/online.html .
310
311
312
313IEEE/The Open Group                  2003                              FORK(P)
Impressum