Unix下的守护进程

此程序在log文件中不停的输出当前系统时间。

 

#include <stdio.h> 
#include <signal.h> 
#include <sys/file.h> 
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <time.h>
void main(int argc,char **argv)
{
	FILE *fileLog;
	char strTMP[512];
	time_t sysTime;
	struct tm *localTime;
	
	int childpid,childpid2,fd,fdtablesize;
	
	/* 忽略终端 I/O信号,STOP信号 */
	signal(SIGTTOU,SIG_IGN);
	signal(SIGTTIN,SIG_IGN);
	signal(SIGTSTP,SIG_IGN); 
	signal(SIGHUP ,SIG_IGN);
			
	/* 父进程退出,程序进入后台运行 */
	childpid = fork();
	if(childpid<0){
		printf("创建子进程失败!");
		exit(1);
	}else if(childpid == 0){		
		/* 创建一个新的会议组 */ 
		if(setsid()<0)
		{
			exit(1);
		}
		
		/* 子进程退出,第二子进程没有控制终端了 */  
		childpid2=fork();
		if(childpid2<0)
		{
			exit(1);
		}else if(childpid2==0){
			if(chdir("./tmp")==-1)
			{
				exit(1);/* 改变当前工作目录 */ 
			}
			
			/* 关闭打开的文件描述符,包括标准输入、标准输出和标准错误输出 */ 
			for (fd = 0, fdtablesize = getdtablesize(); fd < fdtablesize; fd++) 
			close(fd);
			umask(0);/*重设文件创建掩模 */ 
			
			signal(SIGCHLD,SIG_IGN);/* 忽略SIGCHLD信号(子进程退出时会发送此信号给父进程) */ 
			
			
			while(1==1){
				fileLog = fopen("./example.log","a");
				
				if(fileLog == NULL)
				{
					exit(1);
				}
				
				time(&sysTime);
				localTime = localtime(&sysTime);
				
				fprintf(fileLog,"%s log.........\n",asctime(localTime));
				fclose(fileLog);
				sleep(1);				
			}
			fclose(fileLog);
		}else{
			exit(0);
		}
		
	}else{
		printf("父进程结束,子进程id:[%d]\n",childpid);
		exit(0);
	}
}
	


编译makefile:

example:example.o
    xlc_r -o example example.o
example.o:example.c
    xlc_r -c example.c


 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值