1. 程式人生 > >Linux 守護程序

Linux 守護程序

目錄

1. 守護程序是什麼

2. 怎麼用守護程序

2.1 有趣小例子

2.2 man daemon

3. 原始碼解析

3.1 GUN C daemon.c

3.2 daemon.c 解析

3.3 BUGS

4. 後記

1. 守護程序是什麼

Linux Daemon (守護程序) 是執行在後臺的一種特殊程序. 它獨立於控制終端並且週期性地執行某種任務或等待處理

某些發生的事件. 不依賴使用者輸入就能提供某種服務.

Linux 系統中大多數服務都是通過守護程序實現的. 常見的守護程序包括系統日誌程序 syslogd, Web 伺服器 httpd ,

MySQL 資料庫伺服器 mysqld 等. 守護程序的命名我們通常約定以 d 結尾.

2. 怎麼用守護程序

2.1 有趣小例子

#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

//
// gcc -g -O2 -Wall -Wextra -o demo demo.c
// 
int main(void) {
    // 建立守護程序
    if (daemon(0, 0)) {
        perror("daemon error");
        exit(EXIT_FAILURE);
    }

    // 守護程序 構建文字任務
    FILE * txt = fopen("demo.log", "w");
    if (txt) {
        fprintf(txt, "%ld, hello, 世界", time(NULL));
        fclose(txt);
    }

    exit(EXIT_SUCCESS);
}

結果出人意料呢? daemon(0, 0) ~ 通過 GNU C 庫 提供的 api, 輕巧的建立了守護程序.

有心同行也可以將上面素材當做守護程序面試題, 不需要死記硬背, 簡單交流下就可以考察出候選人是否嚴謹和用心.

2.2 man daemon

全貌瞭解 daemon() 函式最簡單方法還是看 man daemon 手冊, 摘錄些一塊學習學習, 溫故溫故. 

DAEMON(3)                  Linux Programmer's Manual                 DAEMON(3)

NAME
       daemon - run in the background

SYNOPSIS
       #include <unistd.h>

       int daemon(int nochdir, int noclose);

   Feature Test Macro Requirements for glibc (see feature_test_macros(7)):

       daemon():
           Since glibc 2.21:
               _DEFAULT_SOURCE
           In glibc 2.19 and 2.20:
               _DEFAULT_SOURCE || (_XOPEN_SOURCE && _XOPEN_SOURCE < 500)
           Up to and including glibc 2.19:
               _BSD_SOURCE || (_XOPEN_SOURCE && _XOPEN_SOURCE < 500)

DESCRIPTION
       The daemon() function is for programs wishing to detach themselves from
       the controlling terminal and run in the background as system daemons.

       If nochdir is zero, daemon()  changes  the  process's  current  working
       directory  to  the root directory ("/"); otherwise, the current working
       directory is left unchanged.

       If noclose is zero, daemon() redirects standard input, standard  output
       and  standard  error  to  /dev/null;  otherwise, no changes are made to
       these file descriptors.

RETURN VALUE
       (This function forks, and if the fork(2)  succeeds,  the  parent  calls
       _exit(2),  so that further errors are seen by the child only.)  On suc‐
       cess daemon() returns zero.  If an error occurs,  daemon()  returns  -1
       and  sets errno to any of the errors specified for the fork(2) and set‐
       sid(2).

ATTRIBUTES
       For  an  explanation  of  the  terms  used   in   this   section,   see
       attributes(7).

       ┌──────────┬───────────────┬─────────┐
       │Interface │ Attribute     │ Value   │
       ├──────────┼───────────────┼─────────┤
       │daemon()  │ Thread safety │ MT-Safe │
       └──────────┴───────────────┴─────────┘
CONFORMING TO
       Not  in POSIX.1.  A similar function appears on the BSDs.  The daemon()
       function first appeared in 4.4BSD.

NOTES
       The glibc implementation can also return -1 when /dev/null  exists  but
       is  not  a  character device with the expected major and minor numbers.
       In this case, errno need not be set.

BUGS
       The GNU C library implementation of this function was taken  from  BSD,
       and  does  not  employ  the  double-fork technique (i.e., fork(2), set‐
       sid(2), fork(2)) that is necessary to ensure that the resulting  daemon
       process  is  not  a session leader.  Instead, the resulting daemon is a
       session leader.  On systems  that  follow  System  V  semantics  (e.g.,
       Linux),  this  means  that  if  the daemon opens a terminal that is not
       already a controlling terminal for another session, then that  terminal
       will inadvertently become the controlling terminal for the daemon.

SEE ALSO
       fork(2), setsid(2), daemon(7), logrotate(8)

COLOPHON
       This  page  is  part of release 4.15 of the Linux man-pages project.  A
       description of the project, information about reporting bugs,  and  the
       latest     version     of     this    page,    can    be    found    at
       https://www.kernel.org/doc/man-pages/.

GNU                               2017-11-26                         DAEMON(3)

翻譯其中核心的幾小段, 有更好翻譯可以提供或者告知, 文章會迅速修正.

NAME
       daemon - 執行在後臺

SYNOPSIS
       #include <unistd.h>

       int daemon(int nochdir, int noclose);

DESCRIPTION
        daemon() 函式希望執行程式脫離控制終端, 作為系統守護程序在後臺執行.

        如果 nochdir 是 0, daemon() 將更改當前程序工作目錄到 "/" 根目錄. 否則保持
        不變.

        如果 noclose 是 0, deamon() 將重定向 STDIN_FILENO 標準輸入, STDOUT_FILENO
        標準輸出, STDERR_FILENO 標準錯誤 到 /dev/null, 否則保持不變.

RETURN VALUE

        函式內部會執行 fork, 如果 fork 成功, 父程序會呼叫 _exit 退出. 執行成功返回 0. 
        發生錯誤時候將返回 -1, errno 的設定依賴 fork(), setsid(), daemon() 原始碼.

3. 原始碼解析

3.1 GUN C daemon.c

glibc-2.33/misc/daemon.c

 1 /*-
 2  * Copyright (c) 1990, 1993
 3  *    The Regents of the University of California.  All rights reserved.
 4  *
 5  * Redistribution and use in source and binary forms, with or without
 6  * modification, are permitted provided that the following conditions
 7  * are met:
 8  * 1. Redistributions of source code must retain the above copyright
 9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 4. Neither the name of the University nor the names of its contributors
14  *    may be used to endorse or promote products derived from this software
15  *    without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29 
30 #if defined(LIBC_SCCS) && !defined(lint)
31 static char sccsid[] = "@(#)daemon.c    8.1 (Berkeley) 6/4/93";
32 #endif /* LIBC_SCCS and not lint */
33 
34 #include <errno.h>
35 #include <fcntl.h>
36 #include <paths.h>
37 #include <unistd.h>
38 #include <sys/stat.h>
39 
40 #include <device-nrs.h>
41 #include <not-cancel.h>
42 
43 int
44 daemon (int nochdir, int noclose)
45 {
46     int fd;
47 
48     switch (__fork()) {
49     case -1:
50         return (-1);
51     case 0:
52         break;
53     default:
54         _exit(0);
55     }
56 
57     if (__setsid() == -1)
58         return (-1);
59 
60     if (!nochdir)
61         (void)__chdir("/");
62 
63     if (!noclose) {
64         struct stat64 st;
65 
66         if ((fd = __open_nocancel(_PATH_DEVNULL, O_RDWR, 0)) != -1
67             && (__builtin_expect (__fstat64 (fd, &st), 0)
68             == 0)) {
69             if (__builtin_expect (S_ISCHR (st.st_mode), 1) != 0
70 #if defined DEV_NULL_MAJOR && defined DEV_NULL_MINOR
71                 && (st.st_rdev
72                 == makedev (DEV_NULL_MAJOR, DEV_NULL_MINOR))
73 #endif
74                 ) {
75                 (void)__dup2(fd, STDIN_FILENO);
76                 (void)__dup2(fd, STDOUT_FILENO);
77                 (void)__dup2(fd, STDERR_FILENO);
78                 if (fd > 2)
79                     (void)__close (fd);
80             } else {
81                 /* We must set an errno value since no
82                    function call actually failed.  */
83                 __close_nocancel_nostatus (fd);
84                 __set_errno (ENODEV);
85                 return -1;
86             }
87         } else {
88             __close_nocancel_nostatus (fd);
89             return -1;
90         }
91     }
92     return (0);
93 }

3.2 daemon.c 解析

30-32 行 SCCS ID (SCCS 代表原始碼控制系統)

66 行 和 88 行 類似 open 和 close

// sysdeps/generic/not-cancel.h

/* By default we have none.  Map the name to the normal functions.  */
#define __open_nocancel(...) \
  __open (__VA_ARGS__)

#define __close_nocancel(fd) \
  __close (fd)

不過 88 行不夠嚴禁, 因為當 fd == -1 時候, 會 __close_nocancel_nostatus (-1) 會引發一個 @errno{EBADF, 9, Bad file descriptor}. 

67 - 73 行 (__builtin_expect (EXP, N) 表達意思是告訴編譯器預測 EXP 表試式 == 常量 N 概率很大,  返回值是 EXP )  大致

意思獲取檔案屬性, 並且不是位元組裝置. makedev 用於構建裝置 id. 

75-77 三行, 將 STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO 控制代碼指向 fd 控制代碼所指向的 dev/null 檔案.

78-79 行, 很漂亮很嚴謹功力很厚.  

3.3 BUGS

在 2.2 中有這段話, 

BUGS
       The GNU C library implementation of this function was taken  from  BSD,
       and  does  not  employ  the  double-fork technique (i.e., fork(2), set‐
       sid(2), fork(2)) that is necessary to ensure that the resulting  daemon
       process  is  not  a session leader.  Instead, the resulting daemon is a
       session leader.  On systems  that  follow  System  V  semantics  (e.g.,
       Linux),  this  means  that  if  the daemon opens a terminal that is not
       already a controlling terminal for another session, then that  terminal
       will inadvertently become the controlling terminal for the daemon.

BUGS

        GNUC 庫 這個 daemon() 函式的實現取自 BSD 原始碼. 沒有采用兩次 double fork
        設定 sid 機制, 來確保生成的守護程序不是會話負責人. 相反, 這裡生成的守護
        程序是會話負責人 (session leader). 在遵循 System V 語義系統上, 建立的守
        護程序在重新開啟終端時候, 新開終端會自動成為守護程序的控制終端.

參照這些內容我們補充一個大致符合 System V 版本 daemon 

/*
 * 建立守護程序
 */
void daemon_service(void) {
    // fork 後父程序 exit 退出, 保證子程序可以成功 setsid() 擁有一個新會話
    switch (fork()) {
    case -1:
        exit(EXIT_FAILURE);
    case 0:
        break;    
    default:
        exit(EXIT_SUCCESS);
    }

    // 子程序建立新會話
    // 執行成功後 Process ID(PID) == Process Group ID(PGID) == Session ID(SID)
    if (setsid() == -1)
        exit(EXIT_FAILURE);

    // 二次 fork 後孫程序不再是會話組首程序, 因而孫程序無法重新開啟一個新的控制終端
    // 執行成功後 Process ID(PID) != Process Group ID(PGID) == Session ID(SID)
    switch (fork()) {
    case -1:
        exit(EXIT_FAILURE);
    case 0:
        break;    
    default:
        exit(EXIT_SUCCESS);
    }

    // 子程序設定新的工作目錄是 根目錄 "/", 避免存在掛載磁碟一直被佔用的情況
    if (chdir("/")) {}

    // 子程序重置 建立檔案 許可權
    umask(0);

    // 相關控制代碼善後, 節省資源
    fflush(stderr);
    fflush(stdout);
    for (int fd = sysconf(_SC_OPEN_MAX); fd >= 0; fd--)
        close(fd);
}

4. 後記

歡迎交流指正 ~

感恩❉ 不忘初心, 與善者同行 ❤&n