目录
题目
创建一个守护进程,循环间隔1s向文件中写入一串字符“hello”
思路
首先,程序中使用
fork
函数创建一个子进程。如果
fork
函数返回值小于 0 ,表示创建子进程失败,通过perror
输出错误信息并返回-1
结束程序。如果是子进程(
pid == 0
):
- 打开或创建一个名为
log.txt
的文件,并设置读写权限、创建新文件、截断文件等标志,同时指定权限为0777
。如果打开文件失败,通过perror
输出错误信息并返回-1
。- 使用
setsid
函数创建一个新的会话,使子进程成为会话组长,脱离原来的控制终端。- 使用
chdir
函数将当前工作目录切换到根目录/
。- 使用
umask
函数设置文件创建掩码为 0 ,以确保创建的文件具有最大权限。- 关闭标准输入(0)、标准输出(1)和标准错误输出(2)这三个文件描述符。
- 进入一个无限循环,每隔 1 秒向打开的文件中写入字符串
"hello"
。如果是父进程(
pid > 0
),直接使用exit(0)
退出。总的来说,这段代码的目的是创建一个子进程,让子进程进行一系列的初始化操作,然后在一个无限循环中向指定文件写入数据,而父进程直接退出。
代码
#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;
}