use-daemon-in-bosserver-and-afsd-20050424
[openafs.git] / src / util / daemon.c
1 #include <afsconfig.h>
2 #include <afs/param.h>
3
4 #ifndef HAVE_DAEMON
5
6 #include <stdio.h>
7 #include <stdlib.h>
8 #include <unistd.h>
9
10 #include <sys/types.h>
11
12 int daemon(int nochdir, int noclose)
13 {
14         int err = -1;
15         pid_t pid;
16
17         pid = fork();
18         if (pid == -1) {
19                 goto out;
20         } else if (pid) {
21                 exit(0);
22         }
23
24         err = setsid();
25         if (err == -1) {
26                 goto out;
27         }
28
29         if (!nochdir) {
30                 err = chdir("/");
31                 if (err == -1) {
32                         goto out;
33                 }
34         }
35
36         err = -1;
37         if (!noclose) {
38                 if (!freopen("/dev/null", "r", stdin)) {
39                         goto out;
40                 }
41
42                 if (!freopen("/dev/null", "w", stdout)) {
43                         goto out;
44                 }
45
46                 if (!freopen("/dev/null", "w", stderr)) {
47                         goto out;
48                 }
49         }
50
51         err = 0;
52
53 out:
54         return(err);
55 }
56 #endif