c - 运行 Linux 守护进程与后台无限循环

标签 c linux daemon

我有这段代码可以在 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 & 运行它。这现在也将作为无限循环在后台运行。

那有什么区别呢?第二个要简单得多。

最佳答案

fork/daemon 方法的一个简单优点是程序员决定 fork 发生的位置,这允许程序员提供保证,当一个人返回 shell 时没有错误,守护进程启动并运行。

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

关于c - 运行 Linux 守护进程与后台无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29497369/

相关文章:

java - commons-daemon procrun & log4j 下如何解释 user.dir 系统属性?

c++ - 如何在 Linux 上将 googleTest 设置为共享库

c - 为什么移动缓冲区指针会减慢 fread(C 编程语言)速度?

c++ - I/O 流操纵器 - 内部调整域 - C++ 与 C

c - 使用 ida pro 打补丁

c++ - 以 root 身份运行应用程序时如何获得 stdio 输出?

linux - 每 10 秒将 bash 输出重定向到新文件

android - 异步任务和守护进程之间的区别

signals - gtk3 - 在 g_application_hold() 期间注销

找不到Mysql库