Last active
November 26, 2016 12:30
-
-
Save phoenixxie0/6265187 to your computer and use it in GitHub Desktop.
一个C语言编写的简易守护进程..
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <time.h> | |
#include <unistd.h> | |
#include <signal.h> | |
#include <sys/param.h> | |
#include <sys/types.h> | |
#include <sys/stat.h> | |
#include <stdlib.h> | |
void init_daemon(void); /*守护进程初始化函数*/ | |
int main(int argc,char* argv[]) | |
{ | |
FILE *fp; | |
time_t t; | |
if(argc != 2) | |
{ | |
printf("please input: ./daemon [path]"); | |
return -1; | |
} | |
init_daemon(); | |
char* path = argv[1]; | |
while(1) | |
{ | |
if((fp=fopen("example.log","a+"))>=0) | |
{ | |
t=time(0); | |
fprintf(fp,"start process[%s] at:%s",path,asctime(localtime(&t))); | |
fflush(fp); | |
int res = system(path); | |
fprintf(fp,"process[%s] end at:%s",path,asctime(localtime(&t))); | |
fprintf(fp,"error:%s",strerror()); | |
fclose(fp); | |
} | |
sleep(10); | |
} | |
} | |
void init_daemon(void) | |
{ | |
pid_t child1,child2; | |
int i; | |
child1=fork(); /*创建子进程*/ | |
if(child1<0) | |
{ | |
perror("创建子进程失败\n"); | |
exit(1); | |
} | |
else if(child1>0) /*结束父进程*/ | |
exit(0); | |
setsid(); /*创建新会话,并担任该会话组的组长*/ | |
chdir("/opt/var/log"); /*改变工作目录到/opt/var/log下*/ | |
umask(0); /*重设文件创建掩码*/ | |
for(i=0;i<NOFILE;i++) /*关闭文件描述符*/ | |
close(i); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment