linux守护进程

linux守护进程_第1张图片linux守护进程_第2张图片

linux守护进程_第3张图片linux守护进程_第4张图片linux守护进程_第5张图片linux守护进程_第6张图片linux守护进程_第7张图片

#include 
#include
#include
#include
#include
#include
#include
#include
#include
#include
void work(int num) {
    time_t tim = time(NULL);
    struct tm *loc = localtime(&tim);
    //char buf[1024];
    //sprintf(buf, "%d-%d-%d %d:%d:%d\n", loc->tm_year, loc->tm_mon, loc->tm_wday, 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));
    close(fd);
}
int main() {
    pid_t pid = fork();
    if(pid > 0) {
        exit(0);
    } else if(pid == 0) {
        setsid();
        umask(022);
        chdir("/home/xiaoliao/");
        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_interval.tv_sec = 2;
        val.it_interval.tv_usec = 0;
        val.it_value.tv_sec = 2;
        val.it_value.tv_usec = 0;
        setitimer(ITIMER_REAL, &val, NULL);
    }
    while(1) {
        sleep(10);
    }
    return 0;
}

你可能感兴趣的:(linux,服务器,运维)