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;
}