需求:写一个守护进程,每隔 2s 获取一次系统时间,将这个时间写入到磁盘文件
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <signal.h>
#include <sys/time.h>
#include <time.h>
#include <fcntl.h>
#include <string.h>
void func(int num) // 回调函数
{
// 将当前时间写入磁盘
time_t curtime; //传出参数
time(&curtime); //获取当前时间curtime
char *pt = ctime(&curtime); //格式化时间
int fd = open("/home/ubuntu/1.txt", O_CREAT | O_WRONLY | O_APPEND, 0664);
write(fd, pt, strlen(pt)+1);
close(fd);
}
int main()
{
pid_t pid = fork();
if(pid > 0)
{
exit(1); // 1.创建子进程,父进程退出
}
else if(pid == 0)
{
setsid(); // 2.子进程创建会话
chdir(“/home/ubuntu”); // 3.改变工作目录
umask(0); // 4.改变掩码
close(0); // 5.关闭文件描述符
close(1);
close(2);
// 6.执行核心操作
// 6.1 信号捕捉 注意:先捕捉,后发信号
struct sigaction act;
act.sa_flags = 0;
act.sa_handler = func;
sigemptyset(&act.sa_mask);
sigaction(SIGALRM, &act, NULL);
// 6.2 设置定时器,发送待捕捉的信号
struct itimerval val = {{2,0},{1,0}};
setitimer(ITIMER_REAL, &val, NULL);
while(1); // 让守护进程一直存活
}
return 0;
}