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 \n", 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

 



如果您觉得阅读本文对您有帮助,请点一下“推荐”按钮,您的“推荐”将是我最大的写作动力!欢迎各位转载,但是未经作者本人同意,转载文章之后必须在文章页面明显位置给出作者和原文连接,否则保留追究法律责任的权利。
posted @   夜行过客  阅读(155)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
历史上的今天:
2017-03-29 VS2013-解决VS2013 4996错误
点击右上角即可分享
微信分享提示