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