以下例子是创建一个守护进程,间隔5s在/tmp目录下写文件
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <string.h>
#include <time.h>
void daemonize()
{
//1. 创建一个子进程,父进程退出,主要就是为setsid做准备
pid_t pid;
pid = fork();
if (pid < 0)
{
printf("fork error\n");
return ;
}
else if (pid > 0)
{
exit(0);
}
//2. 调用setsid创建新会话, 如果不创建新会话的话。原来依附在父进程的会话是终端bash创建的,
//这样在关闭那个终端sh后, 整个会话就会退出
setsid();
//3. 改变当前目录, 只要任意可以随意访问的目录,因为不同的目录挂载有可能
//挂载在不同的文件系统上,为了保证守护进程开机启动不依赖对应的文件系统,
//默认将它改变到/目录上
if (chdir("/") < 0)
{
printf("change dir to '/' error\n");
return;
}
//4. 设置文件掩码, 以免在守护进程运行过程中新创建的文件不适合对应权限
umask(0);
//5. 关闭对应的文件描述符
struct rlimit rlim;
if (getrlimit(RLIMIT_NOFILE, &rlim) < 0)
{
perror("getrlimit");
return ;
}
int i = 0;
for (; i < rlim.rlim_cur; ++i)
{
close(i);
}
//6. 工作代码
int fd = open("/tmp/test.log", O_CREAT | O_RDWR | O_APPEND, 0644);
while(1)
{
//char *ctime(const time_t *timep);
time_t tt = time(NULL);
char *ts = ctime(&tt);
write(fd, ts, strlen(ts));
sleep(5);
}
close(fd);
}
int main(int argc, char **argv)
{
daemonize();
return 0;
}