xref: /freebsd-14.2/lib/libc/sys/fork.2 (revision 554b8bc9)
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.\"
30.Dd August 5, 2021
31.Dt FORK 2
32.Os
33.Sh NAME
34.Nm fork
35.Nd create a new process
36.Sh LIBRARY
37.Lb libc
38.Sh SYNOPSIS
39.In unistd.h
40.Ft pid_t
41.Fn fork void
42.Ft pid_t
43.Fn _Fork void
44.Sh DESCRIPTION
45The
46.Fn fork
47function causes creation of a new process.
48The new process (child process) is an exact copy of the
49calling process (parent process) except for the following:
50.Bl -bullet -offset indent
51.It
52The child process has a unique process ID.
53.It
54The child process has a different parent
55process ID (i.e., the process ID of the parent process).
56.It
57The child process has its own copy of the parent's descriptors,
58except for descriptors returned by
59.Xr kqueue 2 ,
60which are not inherited from the parent process.
61These descriptors reference the same underlying objects, so that,
62for instance, file pointers in file objects are shared between
63the child and the parent, so that an
64.Xr lseek 2
65on a descriptor in the child process can affect a subsequent
66.Xr read 2
67or
68.Xr write 2
69by the parent.
70This descriptor copying is also used by the shell to
71establish standard input and output for newly created processes
72as well as to set up pipes.
73.It
74The child process' resource utilizations
75are set to 0; see
76.Xr setrlimit 2 .
77.It
78All interval timers are cleared; see
79.Xr setitimer 2 .
80.It
81The robust mutexes list (see
82.Xr pthread_mutexattr_setrobust 3 )
83is cleared for the child.
84.It
85The atfork handlers established with the
86.Xr pthread_atfork 3
87function are called as appropriate before fork in the parent process,
88and after the child is created, in parent and child.
89.It
90The child process has only one thread,
91corresponding to the calling thread in the parent process.
92If the process has more than one thread,
93locks and other resources held by the other threads are not released
94and therefore only async-signal-safe functions
95(see
96.Xr sigaction 2 )
97are guaranteed to work in the child process until a call to
98.Xr execve 2
99or a similar function.
100The
101.Fx
102implementation of
103.Fn fork
104provides a usable
105.Xr malloc 3 ,
106and
107.Xr rtld 1
108services in the child process.
109.El
110.Pp
111The
112.Fn fork
113function is not async-signal safe and creates a cancellation point
114in the parent process.
115It cannot be safely used from signal handlers, and the atfork handlers
116established by
117.Xr pthread_atfork 3
118do not need to be async-signal safe either.
119.Pp
120The
121.Fn _Fork
122function creates a new process, similarly to
123.Fn fork ,
124but it is async-signal safe.
125.Fn _Fork
126does not call atfork handlers, and does not create a cancellation point.
127It can be used safely from signal handlers, but then no userspace
128services (
129.Xr malloc 3
130or
131.Xr rtld 1 )
132are available in the child if forked from multi-threaded parent.
133In particular, if using dynamic linking, all dynamic symbols used by the
134child after
135.Fn _Fork
136must be pre-resolved.
137Note: resolving can be done globally by specifying the
138.Ev LD_BIND_NOW
139environment variable to the dynamic linker, or per-binary by passing the
140.Fl z Ar now
141option to the static linker
142.Xr ld 1 ,
143or by using each symbol before the
144.Fn _Fork
145call to force the binding.
146.Sh RETURN VALUES
147Upon successful completion,
148.Fn fork
149and
150.Fn _Fork
151return a value
152of 0 to the child process and return the process ID of the child
153process to the parent process.
154Otherwise, a value of -1 is returned
155to the parent process, no child process is created, and the global
156variable
157.Va errno
158is set to indicate the error.
159.Sh EXAMPLES
160The following example shows a common pattern of how
161.Fn fork
162is used in practice.
163.Bd -literal -offset indent
164#include <err.h>
165#include <stdio.h>
166#include <stdlib.h>
167#include <unistd.h>
168
169int
170main(void)
171{
172	pid_t pid;
173
174	/*
175	 * If child is expected to use stdio(3), state of
176	 * the reused io streams must be synchronized between
177	 * parent and child, to avoid double output and other
178	 * possible issues.
179	 */
180	fflush(stdout);
181
182	switch (pid = fork()) {
183	case -1:
184		err(1, "Failed to fork");
185	case 0:
186		printf("Hello from child process!\en");
187
188		/*
189		 * Since we wrote into stdout, child needs to use
190		 * exit(3) and not _exit(2).  This causes handlers
191		 * registered with atexit(3) to be called twice,
192		 * once in parent, and once in the child.  If such
193		 * behavior is undesirable, consider
194		 * terminating child with _exit(2) or _Exit(3).
195		 */
196		exit(0);
197	default:
198		break;
199	}
200
201	printf("Hello from parent process (child's PID: %d)!\en", pid);
202
203	return (0);
204}
205.Ed
206.Pp
207The output of such a program is along the lines of:
208.Bd -literal -offset indent
209Hello from parent process (child's PID: 27804)!
210Hello from child process!
211.Ed
212.Sh ERRORS
213The
214.Fn fork
215system call will fail and no child process will be created if:
216.Bl -tag -width Er
217.It Bq Er EAGAIN
218The system-imposed limit on the total
219number of processes under execution would be exceeded.
220The limit is given by the
221.Xr sysctl 3
222MIB variable
223.Dv KERN_MAXPROC .
224(The limit is actually ten less than this
225except for the super user).
226.It Bq Er EAGAIN
227The user is not the super user, and
228the system-imposed limit
229on the total number of
230processes under execution by a single user would be exceeded.
231The limit is given by the
232.Xr sysctl 3
233MIB variable
234.Dv KERN_MAXPROCPERUID .
235.It Bq Er EAGAIN
236The user is not the super user, and
237the soft resource limit corresponding to the
238.Fa resource
239argument
240.Dv RLIMIT_NPROC
241would be exceeded (see
242.Xr getrlimit 2 ) .
243.It Bq Er ENOMEM
244There is insufficient swap space for the new process.
245.El
246.Sh SEE ALSO
247.Xr execve 2 ,
248.Xr rfork 2 ,
249.Xr setitimer 2 ,
250.Xr setrlimit 2 ,
251.Xr sigaction 2 ,
252.Xr vfork 2 ,
253.Xr wait 2 ,
254.Xr pthread_atfork 3
255.Sh HISTORY
256The
257.Fn fork
258function appeared in
259.At v1 .
260.Pp
261The
262.Fn _Fork
263function was defined by Austin Group together with the removal
264of a requirement that the
265.Fn fork
266implementation must be async-signal safe.
267The
268.Fn _Fork
269function appeared in
270.Fx 13.1 .
271