如果想让某个进程不因用户、终端和其他的变化而受到影响,则必须把此进程变成守护进程。
编写守护进程的步骤:
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); } else if (pid > 0 ) { printf("The father exit \n"); exit(0); } setsid(); //step 2 chdir("/"); //step 3 umask(0); // step 4 for ( i=0;i< getdtablesize(); i++) // step 5 { close(i); } /**此时创建完守护进程,下面开始正式进入守护进程工作**/ while(1) { if ( (fd = open("/tmp/daemon.log", O_CREAT | O_WRONLY | O_APPEND, 0600)) < 0) { printf("Open the file error .\n"); exit(1); } write(fd, buf, sizeof(buf)); close(fd); sleep(10); } exit(0); }