xref: /openbsd-src/lib/libc/sys/w_fork.c (revision 2777ee89d0e541ec819d05abee114837837abbec)
1 /*	$OpenBSD: w_fork.c,v 1.2 2015/10/25 18:03:17 guenther Exp $ */
2 
3 /*
4  * Copyright (c) 2008 Kurt Miller <kurt@openbsd.org>
5  * Copyright (c) 2008 Philip Guenther <guenther@openbsd.org>
6  * Copyright (c) 2003 Daniel Eischen <deischen@freebsd.org>
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Neither the name of the author nor the names of any co-contributors
15  *    may be used to endorse or promote products derived from this software
16  *    without specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
19  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
22  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28  * SUCH DAMAGE.
29  *
30  * $FreeBSD: /repoman/r/ncvs/src/lib/libc_r/uthread/uthread_atfork.c,v 1.1 2004/12/10 03:36:45 grog Exp $
31  */
32 
33 #include <unistd.h>
34 #include "thread_private.h"
35 #include "atfork.h"
36 
37 pid_t	_thread_fork(void);
38 
39 pid_t
40 fork(void)
41 {
42 	struct atfork_fn *p;
43 	pid_t newid;
44 
45 	/*
46 	 * In the common case the list is empty; remain async-signal-safe
47 	 * then by skipping the locking and just forking
48 	 */
49 	if (TAILQ_FIRST(&_atfork_list) == NULL)
50 		return (_thread_fork());
51 
52 	_ATFORK_LOCK();
53 	TAILQ_FOREACH_REVERSE(p, &_atfork_list, atfork_listhead, fn_next)
54 		if (p->fn_prepare)
55 			p->fn_prepare();
56 
57 	newid = _thread_fork();
58 
59 	if (newid == 0) {
60 		TAILQ_FOREACH(p, &_atfork_list, fn_next)
61 			if (p->fn_child)
62 				p->fn_child();
63 	} else {
64 		TAILQ_FOREACH(p, &_atfork_list, fn_next)
65 			if (p->fn_parent)
66 				p->fn_parent();
67 	}
68 	_ATFORK_UNLOCK();
69 
70 	return (newid);
71 }
72