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