1 /* $OpenBSD: w_fork.c,v 1.3 2016/05/07 19:05:22 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 <tib.h> 34 #include <unistd.h> 35 #include "thread_private.h" 36 #include "atfork.h" 37 38 pid_t 39 WRAP(fork)(void) 40 { 41 struct atfork_fn *p; 42 pid_t newid; 43 44 /* 45 * In the common case the list is empty; remain async-signal-safe 46 * then by skipping the locking and just forking 47 */ 48 if (TAILQ_FIRST(&_atfork_list) == NULL) { 49 if (_thread_cb.tc_fork != NULL) 50 return _thread_cb.tc_fork(); 51 newid = fork(); 52 if (newid == 0) 53 TIB_GET()->tib_tid = getthrid(); 54 return newid; 55 } 56 57 _ATFORK_LOCK(); 58 TAILQ_FOREACH_REVERSE(p, &_atfork_list, atfork_listhead, fn_next) 59 if (p->fn_prepare) 60 p->fn_prepare(); 61 62 if (_thread_cb.tc_fork != NULL) 63 newid = _thread_cb.tc_fork(); 64 else { 65 newid = fork(); 66 if (newid == 0) 67 TIB_GET()->tib_tid = getthrid(); 68 } 69 70 if (newid == 0) { 71 TAILQ_FOREACH(p, &_atfork_list, fn_next) 72 if (p->fn_child) 73 p->fn_child(); 74 } else { 75 TAILQ_FOREACH(p, &_atfork_list, fn_next) 76 if (p->fn_parent) 77 p->fn_parent(); 78 } 79 _ATFORK_UNLOCK(); 80 81 return (newid); 82 } 83 DEF_WRAP(fork); 84