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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
|
#include <unistd.h> #include <signal.h> #include <sys/param.h> #include <sys/types.h> #include <sys/stat.h> void init_daemon( void ) { int pid; int i; /* when:step 1; * what:将daemon放入后台运行; * why:为避免挂起控制终端; * how:在进程中调用fork使父进程终止,让daemon在子进程中后台运行。 */ if (pid=fork()) exit (0); //是父进程,结束父进程 else if (pid< 0) exit (1); //fork失败,退出 /* when:step 2。 * what:脱离控制终端,登陆会话和进程组 * why:当进程是回话组长时setsid()会失败,step1已经确保进程不是会话组长 * how:在子进程中调用setsid() */ setsid(); //PS: 调用成功后进程成为新的会话组长和新的进程组组长,并和原来的登陆会话和进程组脱离,由于会话对控制终端的独占性,进程同时和控制终端脱离。 /* when:step3; * what:禁止进程重新打开控制终端; * why :无终端的会话组长能够重新申请打开一个控制终端; * how :使进程不再是会话组长 */ if (pid=fork()) exit (0); //是第一子进程,结束第一子进程 else if (pid< 0) exit (1); //fork失败,退出 //PS:第一子进程即新会话组组长退出,第二子进程继续,但第二子进程不是新会话组组长 /* when:step4; * what:关闭打开的文件描述符; * why :进程会从创建他的父进程那里继承打开的文件描述符,如不关闭,一方面会浪费系统资源,另一方便还会导致文 件无法删除文件系统无法卸载等无法预料的错误; * how :调用close()关闭打开的文件; */ for (i=0; i< NOFILE; i++) close(i); /* when:step5; * what:改变当前工作目录; * why:进程活动时,其工作目录所在的文件系统不能卸载 * how:一般需要调用chdir()将工作目录改变到根目录 */ chdir( "/" ); /* when:step6; * what:重设文档创建掩码 * why :进程冲创建他得父进程那里继承了文件创建掩码,他可能修改守护进程所创建的文件的读取权限 * how :调用umask(0)清除文件创建掩码 */ umask(0); /* when:step7; * what:处理子进程结束信号SIGCHILD * why :防止子进程变成僵尸进程无法杀死,占用系统资源 * how :在linux下忽略该信号即可 */ signal (SIGCHLD, SIG_IGN); return ; } example.c: int main( void ) { FILE *fp = NULL; time_t t; //初始化为daemon int_daemon(); /* 实际编程中建议使用 daemon(0, 0) */ //daemon(0, 0); while (1){ sleep(60); if ((fp = fopen ( "test.log" , "a" )) > 0){ t = time (0); fprintf (fp, "i'm here at %s\r\n" , asctime ( localtime (&t))); fclose (fp); } } }
|