-
Notifications
You must be signed in to change notification settings - Fork 0
/
create_daemon.c
82 lines (70 loc) · 1.77 KB
/
create_daemon.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/* 1.守护进程: xinetd
作用: 使后台运行, 不是终端子进程
步骤: 创建守护进程, create_daemon, 将当前main函数进程设置为守护进程
1.umask(0),设置文件模式创建屏蔽字设置为0
2.fork, 并退出父进程exit(0)
3.设置新会话setsid()
4.SIGCHLD设置为忽略信号,子进程退出无需提醒父进程
5.fork, 并退出父进程
6.更改工作目录到根目录
7.关闭输入, 重定向输出错误到/dev/null设备, close(0), dup2(fd,1), dup2(fd,1)
2. xinetd为系统提供服务,可以设置进程为守护进程
配置文件/etc/xinetd.conf中添加
instances=n,最多守护60守护进程
includedir /etc/xinetd.d 指定守护进程文件夹
3. 时间服务器
*/
#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int create_daemon()
{
int fd, ret=-1;
pid_t pid;
struct sigaction sa;
//将文件模式创建屏蔽字设置为0
umask(0);
//创建新进程
if ((pid = fork()) < 0) {
printf("fork failed!\n");
return -errno;
} else if (pid != 0) {
exit(0); //退出父进程, 不和终端关联
}
//从这里开始只有子进程
if ((pid = fork()) < 0) {
printf("fork failed!\n");
return -errno;
} else if(pid != 0) {
//如果是父进程, 则退出
exit(0);
}
//从这里开始只有孙进程
//更改工作目录到根目录
if (chdir("/") < 0) {
printf("change dir failed!\n");
return -errno;
}
//关闭输入, 重定向输出和错误到/dev/null设备
close(0);
fd = open("/dev/null", O_RDONLY);
dup2(fd, 1);
dup2(fd, 2);
}
int main()
{
int ret = create_daemon();
if (ret < 0) {
perror("create daemon failed!\n");
return ret;
}
while (1) {
sleep(1);
}
return 0;
}