1 /* $OpenBSD: w_fork.c,v 1.1 2015/04/07 01:27:07 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 /* define and initialize the list */ 38 struct atfork_listhead _atfork_list = TAILQ_HEAD_INITIALIZER(_atfork_list); 39 40 pid_t _thread_fork(void); 41 42 pid_t 43 fork(void) 44 { 45 struct atfork_fn *p; 46 pid_t newid; 47 48 /* 49 * In the common case the list is empty; remain async-signal-safe 50 * then by skipping the locking and just forking 51 */ 52 if (TAILQ_FIRST(&_atfork_list) == NULL) 53 return (_thread_fork()); 54 55 _ATFORK_LOCK(); 56 TAILQ_FOREACH_REVERSE(p, &_atfork_list, atfork_listhead, fn_next) 57 if (p->fn_prepare) 58 p->fn_prepare(); 59 60 newid = _thread_fork(); 61 62 if (newid == 0) { 63 TAILQ_FOREACH(p, &_atfork_list, fn_next) 64 if (p->fn_child) 65 p->fn_child(); 66 } else { 67 TAILQ_FOREACH(p, &_atfork_list, fn_next) 68 if (p->fn_parent) 69 p->fn_parent(); 70 } 71 _ATFORK_UNLOCK(); 72 73 return (newid); 74 } 75