多进程-守护进程

概念

启动

进程脚本

守护进程的父进程

特点

查看守护进程

分类

启动方式

守护进程基本步骤

第一步:创建子进程,父进程退出

第二步:在子进程中创建新对话

第三步:改变当前目录为根目录

第四步:重设文件权限掩码

第五步:关闭文件描述符

第六步:守护进程退出处理

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/wait.h>
#include <fcntl.h>


#define MAXFILE 65535

volatile sig_atomic_t running = 1;

void sigterm_handler(int arg) {
    running = 0;
}

// main
int main(int argc, char *argv[]) {
    pid_t pc;
    int i, fd, len;
    char * buf = "This is a Dameon\n";
    len = strlen(buf);

    // 第一步,创建子进程,父进程退出
    pc = fork();
    if (pc < 0) {
        perror("Error fork:");
        exit(EXIT_FAILURE);
    } else if (pc > 0) {    
        exit(0);    // 父进程退出
    }

    // 第二步,在子进程创建新对话
    setsid();
    // 第三步,改变当前目录为根目录
    chdir("/");
    // 第四步,重设文件权限掩码
    umask(0);
    // 第五步,关闭文件描述符
    for(i = 0; i < MAXFILE; i++) 
        close(i);

    // 第六步,守护进程退出处理
    signal(SIGTERM, sigterm_handler);
    while (running) {
        if ((fd = open("/tmp/dameon.log", O_CREAT | O_WRONLY | O_APPEND, 0600)) < 0) {
            perror("Error open:");
            exit(EXIT_FAILURE);
        }
        write(fd, buf, len + 1);
        close(fd);
        usleep(10 * 1000);
    }
    return 0;
}

posted @ 2022-05-03 01:48  starc的miao  阅读(50)  评论(0)    收藏  举报