最近跳槽,转去简悦了,新公司的技术氛围很好,我要更加努力 ~

有些问题不写博客的时候,以为自己是懂的,但是实际讨论的时候,发现有一些细节还是没有搞清楚,这次试试讲进程怎样 daemon 化。

首先上代码,这次的代码来自于 stackoverflow:http://stackoverflow.com/questions/17954432/creating-a-daemon-in-linux

 1 /*
 2  * daemonize.c
 3  * This example daemonizes a process, writes a few log messages,
 4  * sleeps 20 seconds and terminates afterwards.
 5  */
 6 
 7 #include <stdio.h>
 8 #include <stdlib.h>
 9 #include <unistd.h>
10 #include <signal.h>
11 #include <sys/types.h>
12 #include <sys/stat.h>
13 #include <syslog.h>
14 
15 static void skeleton_daemon()
16 {
17     pid_t pid;
18 
19     /* Fork off the parent process */
20     pid = fork();
21 
22     /* An error occurred */
23     if (pid < 0)
24         exit(EXIT_FAILURE);
25 
26     /* Success: Let the parent terminate */
27     if (pid > 0)
28         exit(EXIT_SUCCESS);
29 
30     /* On success: The child process becomes session leader */
31     if (setsid() < 0)
32         exit(EXIT_FAILURE);
33 
34     /* Catch, ignore and handle signals */
35     //TODO: Implement a working signal handler */
36     signal(SIGCHLD, SIG_IGN);
37     signal(SIGHUP, SIG_IGN);
38 
39     /* Fork off for the second time*/
40     pid = fork();
41 
42     /* An error occurred */
43     if (pid < 0)
44         exit(EXIT_FAILURE);
45 
46     /* Success: Let the parent terminate */
47     if (pid > 0)
48         exit(EXIT_SUCCESS);
49 
50     /* Set new file permissions */
51     umask(0);
52 
53     /* Change the working directory to the root directory */
54     /* or another appropriated directory */
55     chdir("/");
56 
57     /* Close all open file descriptors */
58     int x;
59     for (x = sysconf(_SC_OPEN_MAX); x>0; x--)
60     {
61         close (x);
62     }
63 
64     /* Open the log file */
65     openlog ("firstdaemon", LOG_PID, LOG_DAEMON);
66 }
67 
68 int main()
69 {
70     skeleton_daemon();
71 
72     while (1)
73     {
74         //TODO: Insert daemon code here.
75         syslog (LOG_NOTICE, "First daemon started.");
76         sleep (20);
77         break;
78     }
79 
80     syslog (LOG_NOTICE, "First daemon terminated.");
81     closelog();
82 
83     return EXIT_SUCCESS;
84 }

fork 出子进程后,子进程结束时并不会马上被回收,而是形成一个僵尸进程。因为,父进程需要对子进程的尸体进行回收(以获得子进程的运行结果),如果父进程不关心子进程的状态,可以设置 SIGHLD 信号量的处理为忽略。考虑到不同系统实现不同,对于非 Linux 的系统,即使父进程设置了不关心子进程状态,依然有可能