-
Notifications
You must be signed in to change notification settings - Fork 0
/
daemonize.c
56 lines (47 loc) · 1.03 KB
/
daemonize.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "memcached.h"
int daemonize(int nochdir, int noclose)
{
int fd;
switch (fork()) {
case -1:
return (-1);
case 0:
break;
default:
_exit(EXIT_SUCCESS);
}
if (setsid() == -1)
return (-1);
if (nochdir == 0) {
if(chdir("/") != 0) {
perror("chdir");
return (-1);
}
}
if (noclose == 0 && (fd = open("/dev/null", O_RDWR, 0)) != -1) {
if(dup2(fd, STDIN_FILENO) < 0) {
perror("dup2 stdin");
goto err_cleanup;
}
if(dup2(fd, STDOUT_FILENO) < 0) {
perror("dup2 stdout");
goto err_cleanup;
}
if(dup2(fd, STDERR_FILENO) < 0) {
perror("dup2 stderr");
goto err_cleanup;
}
if(close(fd) < 0) {
perror("close");
return (-1);
}
}
return (0);
err_cleanup:
close(fd);
return (-1);
}