xref: /freebsd/lib/libsys/fork.2 (revision ae07a5805b1906f29e786f415d67bef334557bd3)
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.
141In particular, if using dynamic linking, all dynamic symbols used by the
142child after
143.Fn _Fork
144must be pre-resolved.
145Note: resolving can be done globally by specifying the
146.Ev LD_BIND_NOW
147environment variable to the dynamic linker, or per-binary by passing the
148.Fl z Ar now
149option to the static linker
150.Xr ld 1 ,
151or by using each symbol before the
152.Fn _Fork
153call to force the binding.
154.Sh RETURN VALUES
155Upon successful completion,
156.Fn fork
157and
158.Fn _Fork
159return a value
160of 0 to the child process and return the process ID of the child
161process to the parent process.
162Otherwise, a value of -1 is returned
163to the parent process, no child process is created, and the global
164variable
165.Va errno
166is set to indicate the error.
167.Sh EXAMPLES
168The following example shows a common pattern of how
169.Fn fork
170is used in practice.
171.Bd -literal -offset indent
172#include <err.h>
173#include <stdio.h>
174#include <stdlib.h>
175#include <unistd.h>
176
177int
178main(void)
179{
180	pid_t pid;
181
182	/*
183	 * If child is expected to use stdio(3), state of
184	 * the reused io streams must be synchronized between
185	 * parent and child, to avoid double output and other
186	 * possible issues.
187	 */
188	fflush(stdout);
189
190	switch (pid = fork()) {
191	case -1:
192		err(1, "Failed to fork");
193	case 0:
194		printf("Hello from child process!\en");
195
196		/*
197		 * Since we wrote into stdout, child needs to use
198		 * exit(3) and not _exit(2).  This causes handlers
199		 * registered with atexit(3) to be called twice,
200		 * once in parent, and once in the child.  If such
201		 * behavior is undesirable, consider
202		 * terminating child with _exit(2) or _Exit(3).
203		 */
204		exit(0);
205	default:
206		break;
207	}
208
209	printf("Hello from parent process (child's PID: %d)!\en", pid);
210
211	return (0);
212}
213.Ed
214.Pp
215The output of such a program is along the lines of:
216.Bd -literal -offset indent
217Hello from parent process (child's PID: 27804)!
218Hello from child process!
219.Ed
220.Sh ERRORS
221The
222.Fn fork
223system call will fail and no child process will be created if:
224.Bl -tag -width Er
225.It Bq Er EAGAIN
226The system-imposed limit on the total
227number of processes under execution would be exceeded.
228The limit is given by the
229.Xr sysctl 3
230MIB variable
231.Dv KERN_MAXPROC .
232(The limit is actually ten less than this
233except for the super user).
234.It Bq Er EAGAIN
235The user is not the super user, and
236the system-imposed limit
237on the total number of
238processes under execution by a single user would be exceeded.
239The limit is given by the
240.Xr sysctl 3
241MIB variable
242.Dv KERN_MAXPROCPERUID .
243.It Bq Er EAGAIN
244The user is not the super user, and
245the soft resource limit corresponding to the
246.Fa resource
247argument
248.Dv RLIMIT_NPROC
249would be exceeded (see
250.Xr getrlimit 2 ) .
251.It Bq Er ENOMEM
252There is insufficient swap space for the new process.
253.El
254.Sh SEE ALSO
255.Xr execve 2 ,
256.Xr rfork 2 ,
257.Xr setitimer 2 ,
258.Xr setrlimit 2 ,
259.Xr sigaction 2 ,
260.Xr vfork 2 ,
261.Xr wait 2 ,
262.Xr pthread_atfork 3
263.Sh STANDARDS
264The
265.Fn fork
266and
267.Fn _Fork
268functions conform to
269.St -p1003.1-2024 .
270.Sh HISTORY
271The
272.Fn fork
273function appeared in
274.At v1 .
275The
276.Fn _Fork
277function appeared in
278.Fx 13.1 .
279