【问题标题】:Running a Linux Daemon vs An infinite loop in the background在后台运行 Linux 守护程序与无限循环
【发布时间】:2015-04-07 17:20:04
【问题描述】:

我有这段代码可以在 C 中创建一个守护进程:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>

void main() {
  FILE *fp= NULL;
  pid_t process_id = 0;
  pid_t sid = 0;
  // Create child process
  process_id = fork();
  // Indication of fork() failure
  if (process_id < 0)
  {
    printf("fork failed!\n");
    // Return failure in exit status
    exit(1);
  }
  // PARENT PROCESS. Need to kill it.
  if (process_id > 0)
  {
    printf("process_id of child process %d \n", process_id);
    // return success in exit status
    exit(0);
  }
  //unmask the file mode
  umask(0);
  //set new session
  sid = setsid();
  if(sid < 0)
  {
    // Return failure
    exit(1);
  }
  // Change the current working directory to root.
  chdir("/");
  // Close stdin. stdout and stderr
  close(STDIN_FILENO);
  close(STDOUT_FILENO);
  close(STDERR_FILENO);

  while (1)
  {
    // Do your thing
    usleep(2000);
  }
}

我可以编译并以./exampleOne 运行它,它将永远在后台作为守护进程运行。

现在反过来,如果我有以下示例:

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

void main() {
  while (1)
  {

    // do your thing
    usleep(2000);
  }
}

然后以./exampleTwo &amp; 运行它。这现在也将作为无限循环在后台运行。

那么有什么区别呢?第二个就简单多了。

【问题讨论】:

  • 为什么不创建一些脚本并在 cron 中运行呢? :)
  • 只是一个相关的事情:您应该安装一个信号处理程序或一个事件以有机会正常终止恶魔进程。 “那么有什么区别?” 第一个示例将您的恶魔进程自动带到后台。
  • 不同之处在于 exampleTwo 只会每 2 秒响应任何输入或事件。你能接受吗?
  • @WojciechFrohmberg,因为我需要比 cron 的 1 分钟占空比更快的响应!
  • @WojciechFrohmberg 应该在/etc/inittab 中指定。

标签: c linux daemon


【解决方案1】:

fork/daemon 方法的一个简单优点是程序员可以决定在哪里进行 fork,这允许程序员保证当一个人返回到 shell 时没有错误,守护程序启动并运行。

在后台运行会立即返回到 shell,因此您的守护进程可能仍处于初始化阶段,与它的连接可能会在一段时间内失败。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-23
    • 1970-01-01
    • 2011-03-27
    • 2012-04-30
    • 2012-05-19
    • 1970-01-01
    相关资源
    最近更新 更多