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

#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;
}
上一篇:Youngter-drive(BUUCTF)


下一篇:Java IO流关闭顺序