# 终端
# 进程组
# 会话
# 守护进程
// 创建一个会话,每隔2s获取系统时间,并将时间写入到磁盘文件中 #include <stdio.h> #include <sys/types.h> #include <unistd.h> #include <stdlib.h> #include <sys/stat.h> #include <fcntl.h> #include <sys/time.h> #include <signal.h> #include <time.h> #include <string.h> void handle(int num) { time_t present_time = time(NULL); struct tm *loc = localtime(&present_time); // 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); int a_fd = open("/home/Linux/lesson22/a.txt", O_RDWR | O_CREAT | O_APPEND, 0777); write(a_fd, buf, strlen(buf)); close(a_fd); } int main() { // 创建子进程 pid_t pid = fork(); // 父进程退出 if(pid > 0) { exit(0); } // 子进程创建会话 setsid(); //更改工作目录 chdir("/"); // 关闭、重定向文件描述符 int fd = open("/dev/null", O_RDWR); dup2(fd, STDIN_FILENO); dup2(fd, STDOUT_FILENO); dup2(fd, STDERR_FILENO); struct sigaction act; act.sa_handler = &handle; act.sa_flags = 0; sigemptyset(&act.sa_mask); sigaction(SIGALRM, &act, NULL); struct itimerval new_value; new_value.it_interval.tv_sec = 2; new_value.it_interval.tv_usec = 0; new_value.it_value.tv_sec = 2; new_value.it_value.tv_usec = 0; setitimer(ITIMER_REAL, &new_value, NULL); while(1) { sleep(10); } return 0; }
标签:loc,value,tm,fd,进程,new,include,守护 From: https://www.cnblogs.com/WTSRUVF/p/17367393.html