]> git.pond.sub.org Git - empserver/blob - src/lib/gen/disassoc.c
717f0508a741781a0fc82068a8fbefeea7570391
[empserver] / src / lib / gen / disassoc.c
1 /*
2  *  Empire - A multi-player, client/server Internet based war game.
3  *  Copyright (C) 1986-2006, Dave Pare, Jeff Bailey, Thomas Ruschak,
4  *                           Ken Stevens, Steve McClure
5  *
6  *  This program is free software; you can redistribute it and/or modify
7  *  it under the terms of the GNU General Public License as published by
8  *  the Free Software Foundation; either version 2 of the License, or
9  *  (at your option) any later version.
10  *
11  *  This program is distributed in the hope that it will be useful,
12  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *  GNU General Public License for more details.
15  *
16  *  You should have received a copy of the GNU General Public License
17  *  along with this program; if not, write to the Free Software
18  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  *
20  *  ---
21  *
22  *  See files README, COPYING and CREDITS in the root of the source
23  *  tree for related information and legal notices.  It is expected
24  *  that future projects/authors will amend these files as needed.
25  *
26  *  ---
27  *
28  *  disassoc.c: Boilerplate daemonization code
29  * 
30  *  Known contributors to this file:
31  *     Doug Hay, 1998
32  *     Markus Armbruster, 2005
33  */
34
35 /*
36  * See W. Richard Stevens: UNIX Network Programming, Vol. 1
37  */
38
39 #include <config.h>
40
41 #ifndef _WIN32
42 #include <fcntl.h>
43 #include <sys/types.h>
44 #include <unistd.h>
45 #include "prototypes.h"
46
47 int
48 disassoc(void)
49 {
50     pid_t pid;
51     int i;
52
53     if ((pid = fork()) < 0)
54         return -1;
55     else if (pid)
56         _exit(0);               /* parent */
57
58     /* Become session leader of new session, lose controlling tty */
59     if (setsid() < 0)
60         return -1;
61
62     /* Lose session leader status, so we can't acquire a controlling tty */
63     if ((pid = fork()) < 0)
64         return -1;
65     else if (pid)
66         _exit(0);               /* parent */
67     /* Note: no controlling tty, therefore no SIGHUP sent */
68
69     /* datadir is working directory, that's fine */
70
71     /* We opened a bunch of files already, so just close 0..2 */
72     for (i = 0; i < 3; i++)
73         close(i);
74
75     /* Library code may use 0..2; make sure that's safe */
76     open("/dev/null", O_RDWR);
77     dup(0);
78     dup(0);
79
80     return 0;
81 }
82 #endif