xref: /freebsd-13.1/lib/libc/sys/fork.2 (revision 5d7b6129)
1.\" Copyright (c) 1980, 1991, 1993
2.\"	The Regents of the University of California.  All rights reserved.
3.\"
4.\" Redistribution and use in source and binary forms, with or without
5.\" modification, are permitted provided that the following conditions
6.\" are met:
7.\" 1. Redistributions of source code must retain the above copyright
8.\"    notice, this list of conditions and the following disclaimer.
9.\" 2. Redistributions in binary form must reproduce the above copyright
10.\"    notice, this list of conditions and the following disclaimer in the
11.\"    documentation and/or other materials provided with the distribution.
12.\" 3. Neither the name of the University nor the names of its contributors
13.\"    may be used to endorse or promote products derived from this software
14.\"    without specific prior written permission.
15.\"
16.\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
17.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19.\" ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
20.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26.\" SUCH DAMAGE.
27.\"
28.\"	@(#)fork.2	8.1 (Berkeley) 6/4/93
29.\" $FreeBSD$
30.\"
31.Dd August 5, 2021
32.Dt FORK 2
33.Os
34.Sh NAME
35.Nm fork
36.Nd create a new process
37.Sh LIBRARY
38.Lb libc
39.Sh SYNOPSIS
40.In unistd.h
41.Ft pid_t
42.Fn fork void
43.Ft pid_t
44.Fn _Fork void
45.Sh DESCRIPTION
46The
47.Fn fork
48function causes creation of a new process.
49The new process (child process) is an exact copy of the
50calling process (parent process) except for the following:
51.Bl -bullet -offset indent
52.It
53The child process has a unique process ID.
54.It
55The child process has a different parent
56process ID (i.e., the process ID of the parent process).
57.It
58The child process has its own copy of the parent's descriptors,
59except for descriptors returned by
60.Xr kqueue 2 ,
61which are not inherited from the parent process.
62These descriptors reference the same underlying objects, so that,
63for instance, file pointers in file objects are shared between
64the child and the parent, so that an
65.Xr lseek 2
66on a descriptor in the child process can affect a subsequent
67.Xr read 2
68or
69.Xr write 2
70by the parent.
71This descriptor copying is also used by the shell to
72establish standard input and output for newly created processes
73as well as to set up pipes.
74.It
75The child process' resource utilizations
76are set to 0; see
77.Xr setrlimit 2 .
78.It
79All interval timers are cleared; see
80.Xr setitimer 2 .
81.It
82The robust mutexes list (see
83.Xr pthread_mutexattr_setrobust 3 )
84is cleared for the child.
85.It
86The atfork handlers established with the
87.Xr pthread_atfork 3
88function are called as appropriate before fork in the parent process,
89and after the child is created, in parent and child.
90.It
91The child process has only one thread,
92corresponding to the calling thread in the parent process.
93If the process has more than one thread,
94locks and other resources held by the other threads are not released
95and therefore only async-signal-safe functions
96(see
97.Xr sigaction 2 )
98are guaranteed to work in the child process until a call to
99.Xr execve 2
100or a similar function.
101The
102.Fx
103implementation of
104.Fn fork
105provides a usable
106.Xr malloc 3 ,
107and
108.Xr rtld 1
109services in the child process.
110.El
111.Pp
112The
113.Fn fork
114function is not async-signal safe and creates a cancellation point
115in the parent process.
116It cannot be safely used from signal handlers, and the atfork handlers
117established by
118.Xr pthread_atfork 3
119do not need to be async-signal safe either.
120.Pp
121The
122.Fn _Fork
123function creates a new process, similarly to
124.Fn fork ,
125but it is async-signal safe.
126.Fn _Fork
127does not call atfork handlers, and does not create a cancellation point.
128It can be used safely from signal handlers, but then no userspace
129services (
130.Xr malloc 3
131or
132.Xr rtld 1 )
133are available in the child if forked from multi-threaded parent.
134In particular, if using dynamic linking, all dynamic symbols used by the
135child after
136.Fn _Fork
137must be pre-resolved.
138Note: resolving can be done globally by specifying the
139.Ev LD_BIND_NOW
140environment variable to the dynamic linker, or per-binary by passing the
141.Fl z Ar now
142option to the static linker
143.Xr ld 1 ,
144or by using each symbol before the
145.Fn _Fork
146call to force the binding.
147.Sh RETURN VALUES
148Upon successful completion,
149.Fn fork
150and
151.Fn _Fork
152return a value
153of 0 to the child process and return the process ID of the child
154process to the parent process.
155Otherwise, a value of -1 is returned
156to the parent process, no child process is created, and the global
157variable
158.Va errno
159is set to indicate the error.
160.Sh EXAMPLES
161The following example shows a common pattern of how
162.Fn fork
163is used in practice.
164.Bd -literal -offset indent
165#include <err.h>
166#include <stdio.h>
167#include <stdlib.h>
168#include <unistd.h>
169
170int
171main(void)
172{
173	pid_t pid;
174
175	/*
176	 * If child is expected to use stdio(3), state of
177	 * the reused io streams must be synchronized between
178	 * parent and child, to avoid double output and other
179	 * possible issues.
180	 */
181	fflush(stdout);
182
183	switch (pid = fork()) {
184	case -1:
185		err(1, "Failed to fork");
186	case 0:
187		printf("Hello from child process!\en");
188
189		/*
190		 * Since we wrote into stdout, child needs to use
191		 * exit(3) and not _exit(2).  This causes handlers
192		 * registered with atexit(3) to be called twice,
193		 * once in parent, and once in the child.  If such
194		 * behavior is undesirable, consider
195		 * terminating child with _exit(2) or _Exit(3).
196		 */
197		exit(0);
198	default:
199		break;
200	}
201
202	printf("Hello from parent process (child's PID: %d)!\en", pid);
203
204	return (0);
205}
206.Ed
207.Pp
208The output of such a program is along the lines of:
209.Bd -literal -offset indent
210Hello from parent process (child's PID: 27804)!
211Hello from child process!
212.Ed
213.Sh ERRORS
214The
215.Fn fork
216system call will fail and no child process will be created if:
217.Bl -tag -width Er
218.It Bq Er EAGAIN
219The system-imposed limit on the total
220number of processes under execution would be exceeded.
221The limit is given by the
222.Xr sysctl 3
223MIB variable
224.Dv KERN_MAXPROC .
225(The limit is actually ten less than this
226except for the super user).
227.It Bq Er EAGAIN
228The user is not the super user, and
229the system-imposed limit
230on the total number of
231processes under execution by a single user would be exceeded.
232The limit is given by the
233.Xr sysctl 3
234MIB variable
235.Dv KERN_MAXPROCPERUID .
236.It Bq Er EAGAIN
237The user is not the super user, and
238the soft resource limit corresponding to the
239.Fa resource
240argument
241.Dv RLIMIT_NPROC
242would be exceeded (see
243.Xr getrlimit 2 ) .
244.It Bq Er ENOMEM
245There is insufficient swap space for the new process.
246.El
247.Sh SEE ALSO
248.Xr execve 2 ,
249.Xr rfork 2 ,
250.Xr setitimer 2 ,
251.Xr setrlimit 2 ,
252.Xr sigaction 2 ,
253.Xr vfork 2 ,
254.Xr wait 2 ,
255.Xr pthread_atfork 3
256.Sh HISTORY
257The
258.Fn fork
259function appeared in
260.At v1 .
261.Pp
262The
263.Fn _Fork
264function was defined by Austin Group together with the removal
265of a requirement that the
266.Fn fork
267implementation must be async-signal safe.
268The
269.Fn _Fork
270function appeared in
271.Fx 14.0 .
272