解释来自https://blog.csdn.net/JMW1407/article/details/108412836
cpp
/*
守护进程
每隔两秒过去一下系统时间,将这个时间写入到磁盘文件
*/
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/time.h>
#include<signal.h>
#include <time.h>
#include <stdlib.h>
#include <string.h>
void work() {
time_t tm = time(NULL);
struct tm *loc = localtime(&tm);
// char buf[1024];
// sprintf(buf, "%d-%d-%d %d-%d-%d\n", loc->tm_year, loc->tm_mon, loc->tm_mday, loc->tm_hour, loc->tm_min, loc->tm_sec);
// printf("%s\n", buf);
char * str = asctime(loc);
int fd = open("time.txt", O_RDWR | O_CREAT | O_APPEND, 0664);
write(fd, str, strlen(str));
}
int main() {
pid_t pid = fork();
if(pid > 0) {
exit(0);
}
//讲子进程创建一个会话
setsid();
//设置掩码
umask(022);
//更改工作目录
chdir("/home/xiaowu/");
//关闭 重定向文件描述符
int fd = open("/dev/null", O_RDWR);
dup2(fd, STDIN_FILENO);
dup2(fd, STDOUT_FILENO);
dup2(fd, STDERR_FILENO);
struct sigaction act;
act.sa_flags = 0;
act.sa_handler = work;
sigemptyset(&act.sa_mask);
sigaction(SIGALRM, &act, NULL);
struct itimerval val;
val.it_value.tv_sec = 2;
val.it_value.tv_usec = 0;
val.it_interval.tv_sec = 2;
val.it_interval.tv_usec = 0;
setitimer(ITIMER_REAL, &val, NULL);
while(1) {
}
}