APUE course source code
guowenxue
2 days ago 68826376ee5f47783c644c6604f4411ec747cd7e
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
/*********************************************************************************
 *      Copyright:  (C) 2025 LingYun IoT System Studio
 *                  All rights reserved.
 *
 *       Filename:  daemon.c
 *    Description:  This file daemon() implement example program
 *
 *        Version:  1.0.0(10/28/2025)
 *         Author:  Guo Wenxue <guowenxue@gmail.com>
 *      ChangeLog:  1, Release initial version on "10/28/2025 10:18:29 AM"
 *
 ********************************************************************************/
 
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
 
void my_daemon(void)
{
    pid_t pid;
 
    /* 第一次 fork,让父进程退出 */
    pid = fork();
    if (pid < 0)
        exit(1);
    else if (pid > 0)
        exit(0);  /* 父进程退出 */
 
    /* 创建新会话,脱离控制终端 */
    if (setsid() < 0)
        exit(1);
 
    /* 第二次 fork,防止重新获得终端 */
    pid = fork();
    if (pid < 0)
        exit(1);
    else if (pid > 0)
        exit(0);
 
    /* 修改工作目录为根目录 */
    chdir("/");
 
    /* 重设文件掩码 */
    umask(0);
 
    /* 关闭标准文件描述符 */
    close(STDIN_FILENO);
    close(STDOUT_FILENO);
    close(STDERR_FILENO);
}
 
int main(void)
{
    my_daemon();
 
    /* 守护进程主循环 */
    while (1)
    {
        int fd = open("/tmp/daemon.log", O_WRONLY | O_CREAT | O_APPEND, 0644);
        if (fd >= 0)
        {
            dprintf(fd, "Daemon alive, PID=%d\n", getpid());
            close(fd);
        }
        sleep(5);
    }
 
    return 0;
}