首页 > 技术文章 > 守护进程怎么写,以及作用

lelei 2020-04-02 10:22 原文

Linux守护进程

编写规则

1.创建子进程,父进程退出

2.在子进程中创建新会话

setsid函数就是用于创建一个新的会话,并担任该会话组的组长,调用setsid有下面3个作用。

让进程摆脱原会话的控制

让进程摆脱原进程组的控制

让进程摆脱原控制终端的控制

 

3.改变当前目录为根目录

4.重设文件权限掩码

umask(0)

5.关闭文件描述符
————————————————
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>

#define MAXFILE 65535

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)
    {
        printf("error fork/n");
        exit(1);
    }
    else if (pc > 0)
    {
        exit(0);
    }

    setsid();
    chdir("/");
    umask(0);
    for (i = 0; i < MAXFILE; i++)
    {
        close(i);
    }

    while (1)
    {
        if ((fd = open("/tmp/dameon.log", O_CREAT|O_WRONLY|O_APPEND, 0600)) < 0)
        {
            perror("open");
            exit(1);
        }
        write(fd, buf, len+1);
        close(fd);
        sleep(5);
    }

    return 0;
}

推荐阅读