在Linux中,我想添加一个无法停止的守护进程,它监视文件系统的更改。如果检测到任何更改,它应该将路径写入控制台,并在控制台中启动它+一个新行
守护进程在后台工作,并且(通常…)不属于TTY,这就是为什么不能以您可能想要的方式使用stdout/stderr。
除此之外,还有几个必需的步骤来对进程进行守护
如果我没记错的话,这些步骤是:
给你一个起点:看看这个显示基本步骤的框架代码。此代码现在也可以在GitHub上分叉:Basic skeleton of a linux daemon在
/*
* daemonize.c
* This example daemonizes a process, writes a few log messages,
* sleeps 20 seconds and terminates afterwards.
*/
#include
#include
#include
#include
#include
#include
#include
static void skeleton_daemon()
{
pid_t pid;
/* Fork off the parent process */
pid = fork();
/* An error occurred */
if (pid < 0)
exit(EXIT_FAILURE);
/* Success: Let the parent terminate */
if (pid > 0)
exit(EXIT_SUCCESS);
/* On success: The child process becomes session leader */
if (setsid() < 0)
exit(EXIT_FAILURE);
/* Catch, ignore and handle signals */
//TODO: Implement a working signal handler */
signal(SIGCHLD, SIG_IGN);
signal(SIGHUP, SIG_IGN);
/* Fork off for the second time*/
pid = fork();
/* An error occurred */
if (pid < 0)
exit(EXIT_FAILURE);
/* Success: Let the parent terminate */
if (pid > 0)
exit(EXIT_SUCCESS);
/* Set new file permissions */
umask(0);
/* Change the working directory to the root directory */
/* or another appropriated directory */
chdir("/");
/* Close all open file descriptors */
int x;
for (x = sysconf(_SC_OPEN_MAX); x>=0; x--)
{
close (x);
}
/* Open the log file */
openlog ("firstdaemon", LOG_PID, LOG_DAEMON);
}
int main()
{
skeleton_daemon();
while (1)
{
//TODO: Insert daemon code here.
syslog (LOG_NOTICE, "First daemon started.");
sleep (20);
break;
}
syslog (LOG_NOTICE, "First daemon terminated.");
closelog();
return EXIT_SUCCESS;
}
检查是否一切正常:ps-xj | grep firstdaemon
输出应与此类似:
+------+------+------+------+-----+-------+------+------+------+-----+
| PPID | PID | PGID | SID | TTY | TPGID | STAT | UID | TIME | CMD |
+------+------+------+------+-----+-------+------+------+------+-----+
| 1 | 3387 | 3386 | 3386 | ? | -1 | S | 1000 | 0:00 | ./ |
+------+------+------+------+-----+-------+------+------+------+-----+
您应该在这里看到:
读取系统日志:
执行以下操作:grep firstdaemon/var/log/syslog
输出应与此类似:
firstdaemon[3387]: First daemon started.
firstdaemon[3387]: First daemon terminated.
进一步阅读: