#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
int main(int argc, char const *argv[])
{
pid_t pid;
pid = fork();
if (pid < 0)
{
perror("fork err");
return -1;
}
else if (pid == 0)
{
int fd = open("log.txt", O_RDWR | O_CREAT | O_TRUNC, 0777);
if (fd < 0)
{
perror("open err");
return -1;
}
setsid();
chdir("/");
umask(0);
for (int i = 0; i < 3; i++)
close(i);
while (1)
{
write(fd, "hello", 5);
sleep(1);
}
}
else
{
exit(0);
}
return 0;
}
- 创建子进程,父进程退出。
让子进程变成孤儿进程,成为后台进程; fork()
2. 在子进程中创建新会话
让子进程成为会话组组长并且脱离终端:为了让子进程完全脱离终端;setsid()
3.改变进程运行路径为根目录
原因: 进程运行的路径不能被删除或卸载;chdir("/")
4.函数说明:chdir() 将进程当前的工作目录改变成以参数路径所指的目录4.重设文件权限掩码
目的:增大进程创建文件时权限,提高灵活性;umask(0)
子进程继承了父进程的文件权限掩码,给该子进程使用文件带来一定的影响,因此把文件 权限掩码设置为0,可以增强该守护进程的灵活性。
5. 关闭文件描述符
原因:子进程继承了父进程的一些已经打开了的文件,这些被打开的文件可能永远不会被 守护进程访问,但它们一样占用系统资源,而且还可能导致所在的文件系统无法被卸载。
将不需要的文件关闭:close()