dameon.c

来自「dameon.c 守护进程程序的一个例子」· C语言 代码 · 共 45 行

C
45
字号
/*dameon.c创建守护进程实例*/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<fcntl.h>
#include<sys/types.h>
#include<unistd.h>
#include<sys/wait.h>

#define MAXFILE 65535
int main()
{
	pid_t pc;
	int i,fd,len;
	char *buf="This is a Dameon\n";
	len =strlen(buf);
	/*父进程退出*/
	pc=fork();
	if(pc<0){
		printf("error fork\n");
		exit(1);
	}else if(pc>0)
	exit(0);
	/*在子进程中创建*/
	setsid();
	/*改变当前目录为根目录*/
	chdir("/");
	/*重设文件权限掩码*/
	umask(0);
	/*关闭文件描述符*/
	for(i=0;i<MAXFILE;i++)
		close(i);
	/*这时创建完守护进程,以下开始正式进入守护进程工作*/
	while(1){
		if((fd=open("/tmp/dameon.log",O_CREAT|O_WRONLY|O_APPEND,0600))<0){
			perror("open");
			exit(1);
			}
		write(fd, buf, len+1);
		close(fd);
		sleep(5);
	}
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?