如果想让某个进程不因用户、终端和其他的变化而受到影响,则必须把此进程变成守护进程。
编写守护进程的步骤:
1、创建子进程、父进程退出
2、在子进程中创建新会话
3、改变当前目录为根目录
4、重设文件权限掩码
5、关闭文件描述符
以下为实现守护进程的完整实例,首先按照上述5个步骤,建立了一个守护进程,然后让守护进程每隔10s
向日志文件 /tmp/daemon.log 写入一句话。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
int main()
{
pid_t pid;
int i,fd;
char *buf = "Hello the world \n";
pid = fork(); // step 1
if ( pid < 0 )
{
printf("Error fork \n");
exit(1);