其他程序可以调用void daemon_init(const char * cmd)方法,来初始化当前进程为守候进程
#include<stdio.h>
#include<unistd.h>
#include<sys/resource.h>
#include<fcntl.h>
#include<signal.h>
#include<syslog.h>
void daemon_init(const char * cmd);
int main(int argc, char * argv[])
{
daemon_init("liyachao_d");
time_t ticks;
while(1)
{
sleep(60);
ticks = time(NULL);
syslog(LOG_INFO,"%s",asctime(localtime(&ticks)));
}
return 0;
}
void daemon_init(const char * cmd)
{
int i;
int fd0;
int fd1;
int fd2;
pid_t pid;
struct rlimit rl;
struct sigaction sa;
/*清空文件默认生成权限*/
umask(0);
/*取得最大的文件描述符*/
if(getrlimit(RLIMIT_NOFILE,&rl) < 0 )
{
printf("can't get file limit.");
}
pid = fork();
if(pid < 0 )
{
printf("fork error.");
exit(1);
}
else if(pid > 0)
{
exit(0);
}
setsid();
/*
Ensure future opens won't allocate controlling TTYs.
*/
sa.sa_handler =SIG_IGN;
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
if(sigaction(SIGHUP,&sa,NULL) < 0 )
{
printf("catn't ignore SIGHUP");
exit(1);
}
pid = fork();
if(pid < 0 )
{
printf("child fork error.");
exit(1);
}
else if(pid > 0)
{
exit(0);
}
/*改变工作目录到root*/
if(chdir("/") < 0 )
{
printf("can't change directory to /");
exit(1);
}
/*关闭所有的文件描述符*/
if (rl.rlim_max == RLIM_INFINITY)
{
rl.rlim_max = 1024;
}
for (i = 0; i < rl.rlim_max; i++)
{
close(i);
}
/*重定向文件描述符0,1,2,到/dev/null*/
fd0 = open("/dev/null",O_RDWR);
fd1 = open("/dev/null",O_RDONLY);
fd2 = open("/dev/null",O_RDWR);
openlog(cmd, LOG_CONS, LOG_DAEMON);
/*初始化日志文件*/
if (fd0 != 0 || fd1 != 1 || fd2 != 2)
{
syslog(LOG_ERR, "unexpected file descriptors %d %d %d",fd0, fd1, fd2);
exit(1);
}
}