本文旨在提供守护程序(包括windows,linux)的main函数的模版。
此模版内同时包含Linux守护进程的编写方法。
代码如下
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#ifdef WIN32
#else
#include <signal.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/time.h>
#include <sys/resource.h>
#endif//WIN32
#define VERSION_NO "1.0"
int RunProgram()
{
printf("i am running\n");
// do while loop
return 0;
}
#ifdef WIN32
int RunDaemon()
{
//1 run windows daemon
//2 use CreateMutex to make sure program have only one instance
//3 RunProgram
RunProgram();
return 0;
}
#else
int RunDaemon()
{
struct sigaction act;
struct rlimit rl;
//
pid_t processID = 0;
int status = 0;
int pid = 0;
// ignore signal
act.sa_flags = 0;
act.sa_handler = SIG_IGN;
(void)::sigaction(SIGPIPE, &act, NULL);
(void)::sigaction(SIGHUP, &act, NULL);
(void)::sigaction(SIGINT, &act, NULL);
(void)::sigaction(SIGTERM, &act, NULL);
(void)::sigaction(SIGQUIT, &act, NULL);
(void)::sigaction(SIGALRM, &act, NULL);
//set max file handle count
rl.rlim_cur = 10240;
rl.rlim_max = 10240;
setrlimit(RLIMIT_NOFILE, &rl);
//set core dump size
rl.rlim_cur = RLIM_INFINITY;
rl.rlim_max = RLIM_INFINITY;
setrlimit(RLIMIT_CORE, &rl);
//run in background
if (daemon(0,0) != 0)
{
exit(-1);
}
while(true)
{
processID = fork();
if(processID > 0)
{
status = 0;
while(status==0)
{
pid =::wait(&status);
int exitStatus = WEXITSTATUS(status);
if(WIFEXITED(status) && pid > 0 && status != 0)
{
if(exitStatus == -1)
{
printf("child exit\r\n");
exit(EXIT_FAILURE);
}
printf("[RunDaemon] - WIFEXITED\r\n");
break;
}
if(WIFSIGNALED(status))
{
printf("[RunDaemon] - WIFSIGNALED\r\n");
break;
}
if(WIFSTOPPED(status))
{
printf("[RunDaemon] - WIFSTOPPED\r\n");
break;
}
if(pid == -1 && status == 0)
{
continue;
}
if(pid > 0 && status == 0)
{
printf("[RunDaemon] - status == 0\r\n");
exit(EXIT_SUCCESS);
}
printf("[RunDaemon] - EXIT_FAILURE\r\n");
exit(EXIT_FAILURE);
}
}
else if(processID == 0)
{
break;
}
else
{
exit(EXIT_FAILURE);
}
sleep(1);
}
if(processID != 0)
{
exit(EXIT_SUCCESS);
}
else
{
RunProgram();
}
return 0;
}
#endif//WIN32
int main(int argc, char *argv[])
{
bool bExit = false;
if (
(argc >= 2)
&& (strcmp(argv[1], "-v") == 0)
)
{
printf("MyProgram %s %s %s\r\n", VERSION_NO, __DATE__, __TIME__);
bExit = true;
}
if (!bExit)
{
RunDaemon();
}
return 0;
}