系统相关
首页 > 系统相关> > 守护进程:每秒生成一个日志文件

守护进程:每秒生成一个日志文件

作者:互联网

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <time.h>
#define SIZE  32
void get_time(char file_name[SIZE])
{
    time_t t = time(NULL);
    struct tm *tm = localtime(&t);
    sprintf(file_name, "%d%02d%02d%02d%02d%02d", tm->tm_year+1900, (tm->tm_mon)+1, 
                tm->tm_mday,tm->tm_hour,tm->tm_min,tm->tm_sec);
}
void task() {
    //建立日志目录
    const char *path = "/home/a/workspace/daemon_test/log";
    if(-1 == access(path, F_OK)) mkdir(path, 0775);
    chdir(path);

    //每1秒在目录中生成一个文件
    while(1) 
    {
        sleep(1);
        char file_name[SIZE] = "";
        get_time(file_name);
        int fd = open(file_name, O_RDONLY | O_CREAT, 0664);
        close(fd);
    }
}
int main() {
    //父进程直接退出
    if(fork() > 0) exit(0);
    //子进程建立新会话
    if(-1 == setsid())
    {
        perror("setsid");
        exit(1);
    }
    //设置根目录为当前目录
    chdir("/");
    //设置umask
    umask(0);
    //关闭标准输入输出
    close(STDIN_FILENO);
    close(STDOUT_FILENO);
    close(STDERR_FILENO);
    //核心任务
    task();
    return 0;
}

标签:name,02d%,tm,file,close,日志,include,每秒,守护
来源: https://www.cnblogs.com/rookiezjz/p/15825974.html