2 * Copyright (c) 2009 Robert N. M. Watson
5 * This software was developed at the University of Cambridge Computer
6 * Laboratory with support from a grant from Google, Inc.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 * When a multi-threaded application calls fork(2) from one thread while
34 * another thread is blocked in accept(2), we prefer that the file descriptor
35 * to be returned by accept(2) not appear in the child process. Test this by
36 * creating a thread blocked in accept(2), then forking a child and seeing if
37 * the fd it would have returned is defined in the child or not.
40 #include <sys/socket.h>
43 #include <netinet/in.h>
60 do_accept(__unused void *arg)
64 accept_fd = accept(listen_fd, NULL, NULL);
81 waitpid(pid, NULL, 0);
86 * We will call ftruncate(2) on the next available file descriptor,
87 * listen_fd+1, and get back EBADF if it's not a valid descriptor,
88 * and EINVAL if it is. This (currently) works fine in practice.
90 if (ftruncate(listen_fd + 1, 0) < 0) {
93 else if (errno == EINVAL)
94 errx(1, "file descriptor still open in child");
96 err(1, "unexpected error");
98 errx(1, "ftruncate succeeded");
104 struct sockaddr_in sin;
105 pthread_t accept_thread;
107 listen_fd = socket(PF_INET, SOCK_STREAM, 0);
110 bzero(&sin, sizeof(sin));
111 sin.sin_family = AF_INET;
112 sin.sin_len = sizeof(sin);
113 sin.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
114 sin.sin_port = htons(PORT);
115 if (bind(listen_fd, (struct sockaddr *)&sin, sizeof(sin)) < 0)
117 if (listen(listen_fd, -1) <0)
119 if (pthread_create(&accept_thread, NULL, do_accept, NULL) != 0)
120 err(1, "pthread_create");
121 sleep(1); /* Easier than using a CV. */