如果想在守护进程里定期执行某个任务,一个较为直接的办法是利用 crontab 向守护进程发送信号。下面举例说明。
守护进程代码如下:
[C++] 纯文本查看 复制代码 #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
#define MAXFILE 65535
static void sig_handler_usr(int sig)
{
int len, fd;
char *buf = "This is a Daemon\n";
len = strlen(buf);
if(( fd = open("/tmp/dameon.log", O_CREAT|O_WRONLY|O_APPEND,0600)) < 0 ) {
perror("open");
exit(1);
}
write(fd, buf, len + 1);
close(fd);
}
int main()
{
pid_t pc;
int i;
pc = fork();
if( pc < 0 ) {
printf("error fork\n");
exit(1);
} else if ( pc > 0 )
exit(0); /*在父进程里,父进程退出*/
setsid();
chdir("/");
umask(0);
for( i = 0; i< MAXFILE; i++ )
close(i);
signal(SIGUSR1, sig_handler_usr); //安装信号
while(1) {
sleep(10);
}
}
上面进程安装了一个 SIGUSR1 的信号处理函数。那么我们可以从 crontab 里设定一个定时任务,使其定时给守护进程发送信号,如 crontab 的内容如下:22 23 * * * sh /root/signal.sh 上面定时在每晚的 23:22 这个时间里执行 signal.sh 这个脚本,在该脚本中获取守护进程 PID,然后向其发送信号,脚本内容如下:
[Bash shell] 纯文本查看 复制代码 #!/bin/sh
pid=`ps aux |grep '\.\/mydaemon' |awk '{print $2}'`
kill -s 10 $pid |