Linux--守护进程

以下例子是创建一个守护进程,间隔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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值