struct/dstr-putf.c: Remove apparently redundant inclusion of <math.h>.
[mLib] / sys / daemonize.c
1 /* -*-c-*-
2 *
3 * Become a daemon, detaching from terminals
4 *
5 * (c) 2007 Straylight/Edgeware
6 */
7
8 /*----- Licensing notice --------------------------------------------------*
9 *
10 * This file is part of the mLib utilities library.
11 *
12 * mLib is free software; you can redistribute it and/or modify
13 * it under the terms of the GNU Library General Public License as
14 * published by the Free Software Foundation; either version 2 of the
15 * License, or (at your option) any later version.
16 *
17 * mLib is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU Library General Public License for more details.
21 *
22 * You should have received a copy of the GNU Library General Public
23 * License along with mLib; if not, write to the Free
24 * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
25 * MA 02111-1307, USA.
26 */
27
28 /*----- Header files ------------------------------------------------------*/
29
30 #include <sys/types.h>
31 #include <unistd.h>
32 #include <fcntl.h>
33 #include <sys/ioctl.h>
34
35 #include "daemonize.h"
36
37 /*----- Main code ---------------------------------------------------------*/
38
39 /* --- @detachtty@ --- *
40 *
41 * Arguments: ---
42 *
43 * Returns: ---
44 *
45 * Use: Detaches from the current terminal and ensures it can never
46 * acquire a new one. Calls @fork@.
47 */
48
49 void detachtty(void)
50 {
51 #ifdef TIOCNOTTY
52 {
53 int fd;
54 if ((fd = open("/dev/tty", O_RDONLY)) >= 0) {
55 ioctl(fd, TIOCNOTTY);
56 close(fd);
57 }
58 }
59 #endif
60 setsid();
61 if (fork() > 0)
62 _exit(0);
63 }
64
65 /* --- @daemonize@ --- *
66 *
67 * Arguments: ---
68 *
69 * Returns: Zero if OK, nonzero on failure.
70 *
71 * Use: Becomes a daemon.
72 */
73
74 int daemonize(void)
75 {
76 pid_t kid;
77
78 if ((kid = fork()) < 0)
79 return (-1);
80 if (kid)
81 _exit(0);
82 detachtty();
83 return (0);
84 }
85
86 /*----- That's all, folks -------------------------------------------------*/