linux 守护进程 函数,在Linux中创建守护进程

在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.

进一步阅读:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值