怎么用守护进程

1. 守护进程是什么

Linux Daemon (守护进程) 是运行在后台的一种特殊进程. 它独立于控制终端并且周期性地执行某种任务或等待处理

某些发生的事件. 不依赖用户输入就能提供某种服务.

Linux 系统中大多数服务都是通过守护进程实现的. 常见的守护进程包括系统日志进程 syslogd, Web 服务器 httpd ,

MySQL 数据库服务器 mysqld 等. 守护进程的命名我们通常约定以 d 结尾.

2. 怎么用守护进程

2.1 有趣小例子

#include #include #include #include //// gcc -g -O2 -Wall -Wextra -o demo demo.c//intmain(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 copyright11 *    notice, this list of conditions and the following disclaimer in the12 *    documentation and/or other materials provided with the distribution.13 * 4. Neither the name of the University nor the names of its contributors14 *    may be used to endorse or promote products derived from this software15 *    without specific prior written permission.16 *17 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE20 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF27 * SUCH DAMAGE.28*/2930#ifdefined(LIBC_SCCS) && !defined(lint)31staticcharsccsid[] ="@(#)daemon.c    8.1 (Berkeley) 6/4/93";32#endif/* LIBC_SCCS and not lint */3334#include 35#include 36#include 37#include 38#include 3940#include 41#include 4243int44daemon (intnochdir,int noclose)45{46int fd;4748switch (__fork()) {49case-1:50return(-1);51case0:52break;53default:54_exit(0);55    }5657if(__setsid() == -1)58return(-1);5960if(!nochdir)61(void)__chdir("/");6263if(!noclose) {64struct stat64 st;6566if((fd = __open_nocancel(_PATH_DEVNULL, O_RDWR,0)) != -167&& (__builtin_expect (__fstat64 (fd, &st),0)68==0)) {69if(__builtin_expect (S_ISCHR (st.st_mode),1) !=070#ifdefined DEV_NULL_MAJOR && defined DEV_NULL_MINOR71&& (st.st_rdev72== makedev (DEV_NULL_MAJOR, DEV_NULL_MINOR))73#endif74                ) {75(void)__dup2(fd, STDIN_FILENO);76(void)__dup2(fd, STDOUT_FILENO);77(void)__dup2(fd, STDERR_FILENO);78if(fd >2)79(void)__close (fd);80}else {81/* We must set an errno value since no82                  function call actually failed.  */83                __close_nocancel_nostatus (fd);84                __set_errno (ENODEV);85return-1;86            }87}else {88            __close_nocancel_nostatus (fd);89return-1;90        }91    }92return(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 foranother 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

正在上传... 取消

/* * 创建守护进程

*/voiddaemon_service(void) {

    // fork 后父进程 exit 退出, 保证子进程可以成功 setsid() 拥有一个新会话switch (fork()) {

    case-1:

        exit(EXIT_FAILURE);

    case0:

        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);

    case0:

        break; 

    default:

        exit(EXIT_SUCCESS);

    }

    // 子进程设置新的工作目录是 根目录 "/", 避免存在挂载磁盘一直被占用的情况if(chdir("/")) {}

    // 子进程重置 创建文件 权限umask(0);

    // 相关句柄善后, 节省资源    fflush(stderr);

    fflush(stdout);

    for(intfd = sysconf(_SC_OPEN_MAX); fd >=0; fd--)

        close(fd);

}

深圳网站建设www.sz886.com

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,869评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,716评论 3 396
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 166,223评论 0 357
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,047评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,089评论 6 395
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,839评论 1 308
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,516评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,410评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,920评论 1 319
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,052评论 3 340
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,179评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,868评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,522评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,070评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,186评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,487评论 3 375
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,162评论 2 356

推荐阅读更多精彩内容