7.守护进程

一.守护进程编程模型

1. 创建子进程,父进程退出
  所有工作在子进程中进行
  形式上脱离了控制终端
2. 在子进程中创建新会话
  setsid()函数
  使子进程完全独立出来,脱离控制
3. 改变当前目录为根目录
  chdir()函数
  防止占用可卸载的文件系统
  也可以换成其它路径
4. 重设文件权限掩码
  umask()函数
  防止继承的文件创建屏蔽字拒绝某些权限(最终继承的文件屏蔽字是从shell进程继承下来的,防止继承的文件创建屏蔽字拒绝某些权限)
  增加守护进程灵活性
5. 关闭文件描述符
  继承的打开文件不会用到,浪费系统资源,无法卸载
6. 开始执行守护进程核心工作
7. 守护进程退出处理

二.代码模型

每隔10s在/tmp/damon.log中写入当前时间

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <errno.h>
#include <time.h>
#include <string.h>
#include <dirent.h>


void daemonsize()
{
    pid_t pid;
    if ((pid = fork()) < 0) {
        perror("fork");
        exit(1);    
    } else if (pid != 0) {
        exit(3);
    }

    setsid();

    umask(0);

    if (chdir("/") < 0) {
        perror("chdir");
        exit(2);
    }    

    close(0);
    open("/dev/null", O_RDWR);
    dup2(0, 1);
    dup2(0, 2);
}


int main()
{
    daemonsize();
    /*write current time to /tmp/dameon.log*/
    DIR *dir;    
    if ((dir=opendir("tmp")) == NULL) {
        if (errno == ENOENT) {
            if (mkdir("./tmp", 0777)<0) {
                perror("mkdir");
                exit(4);
            }
        } else {
            perror("opendir");
            exit(6);
        }
    }

    int fd;
    umask(0);
    fd = open("./tmp/daemon.log", O_CREAT | O_RDWR, 0777);
    if (fd < 0) {
        perror("open");
        exit(5);
    }

    char buf[1024] = {0};

    while(1) {
        time_t timep;
        if (time(&timep) < 0) {
            perror("time");
            exit(6);
        }

        struct tm *now;
        now = localtime(&timep);
        memset(buf, 0, sizeof(buf));
        strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S 
", now);
        write(fd, buf, strlen(buf));

        sleep(10);
    }

    return 0;
}

打开/tmp/damon.log文件

2018-03-29 14:54:29
2018-03-29 14:54:39
2018-03-29 14:54:49
2018-03-29 14:54:59
2018-03-29 14:55:09
2018-03-29 14:55:19
2018-03-29 14:55:29
2018-03-29 14:55:39
2018-03-29 14:55:49
2018-03-29 14:55:59
2018-03-29 14:56:09
2018-03-29 14:56:19
2018-03-29 14:56:29
2018-03-29 14:56:39
2018-03-29 14:56:49
2018-03-29 14:56:59
2018-03-29 14:57:09
2018-03-29 14:57:19
2018-03-29 14:57:29
2018-03-29 14:57:39
2018-03-29 14:57:49
2018-03-29 14:57:59
2018-03-29 14:58:09
2018-03-29 14:58:19
2018-03-29 14:58:29
2018-03-29 14:58:39
2018-03-29 14:58:49
2018-03-29 14:58:59

原文地址:https://www.cnblogs.com/yongdaimi/p/8669880.html