【发布时间】: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 & 运行它。这现在也将作为无限循环在后台运行。
那么有什么区别呢?第二个就简单多了。
【问题讨论】:
-
为什么不创建一些脚本并在 cron 中运行呢? :)
-
只是一个相关的事情:您应该安装一个信号处理程序或一个事件以有机会正常终止恶魔进程。 “那么有什么区别?” 第一个示例将您的恶魔进程自动带到后台。
-
不同之处在于 exampleTwo 只会每 2 秒响应任何输入或事件。你能接受吗?
-
@WojciechFrohmberg,因为我需要比 cron 的 1 分钟占空比更快的响应!
-
@WojciechFrohmberg 应该在
/etc/inittab中指定。