您的位置:首页 > 运维架构 > Linux

linux守护进程代码分析

2016-10-15 01:21 288 查看
1. 创建子进程, 将父进程关闭, 此时子进程的资源回收问题将交给init进程进行销毁2. setsid() 创建新的会话, 将子进程完全独立出来3. chdir() 将子进程的当前路径位置改变成 根目录 (防止子进程路径为挂载路径)4. umask() 将系统创建默认权限置 05. 将所有的文件描述符关闭或者尽量减少文件描述符的存在(文件描述符浪费资源)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;//forkpid = fork();if (pid < 0){perror("fork");exit(-2);}else if (pid > 0){exit(0);}//setsidsetsid();//chdirret = chdir("/");if (ret < 0){perror("chdir");exit(-3);}//umaskumask(0);//fdclose (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;}
                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息