主頁 > 作業系統 > Linux 守護行程

Linux 守護行程

2021-03-04 06:08:37 作業系統

目錄

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. 后記

歡迎交流指正 ~

感恩? 不忘初心, 與善者同行 ? 

轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/265796.html

標籤:其他

上一篇:STM32 SDIO詳解

下一篇:ELK----elasticsearch7.10.1安裝配置

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • CA和證書

    1、在 CentOS7 中使用 gpg 創建 RSA 非對稱密鑰對 gpg --gen-key #Centos上生成公鑰/密鑰對(存放在家目錄.gnupg/) 2、將 CentOS7 匯出的公鑰,拷貝到 CentOS8 中,在 CentOS8 中使用 CentOS7 的公鑰加密一個檔案 gpg -a ......

    uj5u.com 2020-09-10 00:09:53 more
  • Kubernetes K8S之資源控制器Job和CronJob詳解

    Kubernetes的資源控制器Job和CronJob詳解與示例 ......

    uj5u.com 2020-09-10 00:10:45 more
  • VMware下安裝CentOS

    VMware下安裝CentOS 一、軟硬體準備 1 Centos鏡像準備 1.1 CentOS鏡像下載地址 下載地址 1.2 CentOS鏡像下載程序 點擊下載地址進入如下圖的網站,選擇需要下載的版本,這里選擇的是Centos8,點擊如圖所示。 決定選擇Centos8后,選擇想要的鏡像源進行下載,此 ......

    uj5u.com 2020-09-10 00:12:10 more
  • 如何使用Grep命令查找多個字串

    如何使用Grep 命令查找多個字串 大家好,我是良許! 今天向大家介紹一個非常有用的技巧,那就是使用 grep 命令查找多個字串。 簡單介紹一下,grep 命令可以理解為是一個功能強大的命令列工具,可以用它在一個或多個輸入檔案中搜索與正則運算式相匹配的文本,然后再將每個匹配的文本用標準輸出的格式 ......

    uj5u.com 2020-09-10 00:12:28 more
  • git配置http代理

    git配置http代理 經常遇到克隆 github 慢的問題,這里記錄一下幾種配置 git 代理的方法,解決 clone github 過慢。 目錄 git配置代理 git單獨配置github代理 git配置全域代理 配置終端環境變數 git配置代理 主要使用 git config 命令 git單獨 ......

    uj5u.com 2020-09-10 00:12:33 more
  • Linux npm install 裝包時提示Error EACCES permission denied解

    npm install 裝包時提示Error EACCES permission denied解決辦法 ......

    uj5u.com 2020-09-10 00:12:53 more
  • Centos 7下安裝nginx,使用yum install nginx,提示沒有可用的軟體包

    Centos 7下安裝nginx,使用yum install nginx,提示沒有可用的軟體包。 18 (flaskApi) [root@67 flaskDemo]# yum -y install nginx 19 已加載插件:fastestmirror, langpacks 20 Loading ......

    uj5u.com 2020-09-10 00:13:13 more
  • Linux查看服務器暴力破解ssh IP

    在公網的服務器上經常遇到別人爆破你服務器的22埠,用來挖礦或者干其他嘿嘿嘿的事情~ 這種情況下正確的做法是: 修改默認ssh的22埠 使用設定密鑰登錄或者白名單ip登錄 建議服務器密碼為復雜密碼 創建普通用戶登錄服務器(root權限過大) 建立堡壘機,實作統一管理服務器 統計爆破IP [root ......

    uj5u.com 2020-09-10 00:13:17 more
  • CentOS 7系統常見快捷鍵操作方式

    Linux系統中一些常見的快捷方式,可有效提高操作效率,在某些時刻也能避免操作失誤帶來的問題。 ......

    uj5u.com 2020-09-10 00:13:31 more
  • CentOS 7作業系統目錄結構介紹

    作業系統存在著大量的資料檔案資訊,相應檔案資訊會存在于系統相應目錄中,為了更好的管理資料資訊,會將系統進行一些目錄規劃,不同目錄存放不同的資源。 ......

    uj5u.com 2020-09-10 00:13:35 more
最新发布
  • vim的常用命令

    Vim的6種基本模式 1. 普通模式在普通模式中,用的編輯器命令,比如移動游標,洗掉文本等等。這也是Vim啟動后的默認模式。這正好和許多新用戶期待的操作方式相反(大多數編輯器默認模式為插入模式)。 2. 插入模式在這個模式中,大多數按鍵都會向文本緩沖中插入文本。大多數新用戶希望文本編輯器編輯程序中一 ......

    uj5u.com 2023-04-20 08:43:21 more
  • vim的常用命令

    Vim的6種基本模式 1. 普通模式在普通模式中,用的編輯器命令,比如移動游標,洗掉文本等等。這也是Vim啟動后的默認模式。這正好和許多新用戶期待的操作方式相反(大多數編輯器默認模式為插入模式)。 2. 插入模式在這個模式中,大多數按鍵都會向文本緩沖中插入文本。大多數新用戶希望文本編輯器編輯程序中一 ......

    uj5u.com 2023-04-20 08:42:36 more
  • docker學習

    ###Docker概述 真實專案部署環境可能非常復雜,傳統發布專案一個只需要一個jar包,運行環境需要單獨部署。而通過Docker可將jar包和相關環境(如jdk,redis,Hadoop...)等打包到docker鏡像里,將鏡像發布到Docker倉庫,部署時下載發布的鏡像,直接運行發布的鏡像即可。 ......

    uj5u.com 2023-04-19 09:26:53 more
  • 設定Windows主機的瀏覽器為wls2的默認瀏覽器

    這里以Chrome為例。 1. 準備作業 wsl是可以使用Windows主機上安裝的exe程式,出于安全考慮,默認情況下改功能是無法使用。要使用的話,終端需要以管理員權限啟動。 我這里以Windows Terminal為例,介紹如何默認使用管理員權限打開終端,具體操作如下圖所示: 2. 操作 wsl ......

    uj5u.com 2023-04-19 09:25:49 more
  • docker學習

    ###Docker概述 真實專案部署環境可能非常復雜,傳統發布專案一個只需要一個jar包,運行環境需要單獨部署。而通過Docker可將jar包和相關環境(如jdk,redis,Hadoop...)等打包到docker鏡像里,將鏡像發布到Docker倉庫,部署時下載發布的鏡像,直接運行發布的鏡像即可。 ......

    uj5u.com 2023-04-19 09:19:04 more
  • Linux學習筆記

    IP地址和主機名 IP地址 ifconfig可以用來查詢本機的IP地址,如果不能使用,可以通過install net-tools安裝。 Centos系統下ens33表示主網卡;inet后表示IP地址;lo表示本地回環網卡; 127.0.0.1表示代指本機;0.0.0.0可以用于代指本機,同時在放行設 ......

    uj5u.com 2023-04-18 06:52:01 more
  • 解決linux系統的kdump服務無法啟動的問題

    問題:專案麒麟系統服務器的kdump服務無法啟動,沒有相關日志無法定位問題。 1、查看服務狀態是關閉的,重啟系統也無法啟動 systemctl status kdump 2、修改grub引數,修改“crashkernel”為“512M(有的機器數值太大太小都會導致報錯,建議從128M開始試,或者加個 ......

    uj5u.com 2023-04-12 09:59:50 more
  • 解決linux系統的kdump服務無法啟動的問題

    問題:專案麒麟系統服務器的kdump服務無法啟動,沒有相關日志無法定位問題。 1、查看服務狀態是關閉的,重啟系統也無法啟動 systemctl status kdump 2、修改grub引數,修改“crashkernel”為“512M(有的機器數值太大太小都會導致報錯,建議從128M開始試,或者加個 ......

    uj5u.com 2023-04-12 09:59:01 more
  • 你是不是暴露了?

    作者:袁首京 原創文章,轉載時請保留此宣告,并給出原文連接。 如果您是計算機相關從業人員,那么應該經歷不止一次網路安全專項檢查了,你肯定是收到過資訊系統技術檢測報告,要求你加強風險監測,確保你提供的系統服務堅實可靠了。 沒檢測到問題還好,檢測到問題的話,有些處理起來還是挺麻煩的,尤其是線上正在運行的 ......

    uj5u.com 2023-04-05 16:52:56 more
  • 細節拉滿,80 張圖帶你一步一步推演 slab 記憶體池的設計與實作

    1. 前文回顧 在之前的幾篇記憶體管理系列文章中,筆者帶大家從宏觀角度完整地梳理了一遍 Linux 記憶體分配的整個鏈路,本文的主題依然是記憶體分配,這一次我們會從微觀的角度來探秘一下 Linux 內核中用于零散小記憶體塊分配的記憶體池 —— slab 分配器。 在本小節中,筆者還是按照以往的風格先帶大家簡單 ......

    uj5u.com 2023-04-05 16:44:11 more