我有这段代码可以在 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/