实现守护进程

来源:互联网 发布:百度seo 价格 编辑:程序博客网 时间:2024/06/05 10:20
系统有这个函数,叫daemom,我进行了模拟手动实现
#include <stdio.h>#include <sys/types.h>#include <sys/stat.h>#include <unistd.h>#include <fcntl.h>#include <stdlib.h>int daemonize(int nochdir,int noclose);{//创建子进程,关闭父进程int pid = fork();if(pid > 0){exit(0);}if(pid == -1)return -1;//设置文件的掩码 mode & ~umaskumask(0);//设置文件新的回话if(setsid() < 0){perror("setsid");return -1;}//设置新的目录if(nochdir == 0){chdir("/");}//关闭标准输入,输出,错误close(STDIN_FILENO);close(STDOUT_FILENO);close(STDERR_FILENO);//重定向if(noclose == 0){open("/dev/null",O_RDWR);open("/dev/null",O_RDWR);open("/dev/null",O_RDWR);}}int main(){// 系统自带的 daemomdaemonize(0,0);while(1);return 0;}