23,110
社区成员
发帖
与我相关
我的任务
分享
#include<stdio.h>
#include<sys/types.h>
#include<sys/param.h>
#include<unistd.h>
#include<signal.h>
#include<sys/stat.h>
#include<time.h>
#include<syslog.h>
#include <dlfcn.h>
#include <errno.h>
int daemon_init(void)
{
pid_t pid;
int fd;
int i;
pid = fork();
if(pid<0)
{
perror("Fail to creat child process.\n");
return -1;
}
else if(pid>0)
{
printf("daemon parent exit,pid = %d\n",pid);
exit(0);//结束父进程,使得子进程成为后台进程
}
setsid();//建立一个新的进程组
pid = fork();
if(pid<0)
{
perror("Setsid failed.\n");
return -1;
}
else if(pid > 0)
{
exit(0);
}
for(i = 0; i < NOFILE; close(i++));
chdir("/");
umask(0);
return 0;
}
void sig_term(int signo)
{
if(signo == SIGINT)
/* catched signal sent by kill(1) command */
{
syslog(LOG_INFO, "program terminated.");
closelog();
exit(0);
}
}
int main(int argc,char **argv)
{
time_t now;
if(argc == 2)
{
if(!strcmp(argv[1],"-a"))
{
if(daemon_init() == -1)
{
printf("can't fork self\n");
exit(0);
}
openlog("Test", LOG_PID, LOG_USER);
syslog(LOG_INFO, "program started.");
signal(SIGTERM, sig_term); /* arrange to catch the signal */
while(1)
{
sleep(8);
time(&now);
syslog(LOG_USER|LOG_INFO,"系统时间: \t%s\t\n",ctime(&now));
}
}
return 0;
}
time(&now);
syslog(LOG_USER|LOG_INFO,"系统时间2: \t%s\t\n",ctime(&now));
}