linux守护进程代码分析


1. 创建子进程, 将父进程关闭, 此时子进程的资源回收问题将交给init进程进行销毁

2. setsid() 创建新的会话, 将子进程完全独立出来

3. chdir() 将子进程的当前路径位置改变成 根目录 (防止子进程路径为挂载路径)

4. umask() 将系统创建默认权限置 0

5. 将所有的文件描述符关闭或者尽量减少文件描述符的存在(文件描述符浪费资源)

6. 子进程的核心功能(守护进程的核心部位)

7. 守护进程的结束

#include <stdio.h>
#include <string.h>
#include <time.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
//每隔10s就向 tmp/daemon.log 写入时间
void _daemon()
{
    pid_t pid;
    int fd = 0;
    int ret = 0;
    //fork
    pid = fork();
    if (pid < 0)
    {
        perror("fork");
        exit(-2);
    }
    else if (pid > 0)
    {
        exit(0);
    }
    //setsid
    setsid();
    //chdir
    ret = chdir("/");
    if (ret < 0)
    {
        perror("chdir");
        exit(-3);
    }
    //umask
    umask(0);
    //fd
    close (0);
    fd = open("/dev/null", O_WRONLY);
    ret = dup2(0, 1);
    if (ret < 0)
    {
        perror("dup2");
        exit(-4);
    }
    dup2(0, 2);
    if (ret < 0)
    {
        perror("dup2");
        exit(-5);
    }
}
int main(void)
{
    int ret = 0;
    int i = 0;
    int fd = 0;
    time_t timep;
    char *str = NULL;
    int len = 0;

    fd = open("/tmp/daemon.log", O_CREAT | O_RDWR, 0777);
    if (fd < 0)
    {
        perror("open");
        exit(-1);
    }
    _daemon();
    while (1)
    {
        sleep(10);
        time(&timep);
        str = ctime(&timep);
        len = strlen(str);
        ret = write(fd, str, len);
        if (ret < 0)
        {
            perror("write");
            exit(-6);
        }
        i++;
        if (5 == i)
        {
            close(fd);
            break;
        }
    }
    return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值