守候进程main函数模版及linux守护写法
2014-02-04 18:33
316 查看
本文旨在提供守护程序(包括windows,linux)的main函数的模版。
此模版内同时包含Linux守护进程的编写方法。
代码如下
此模版内同时包含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; }
相关文章推荐
- linux上编写守护进程的例程
- 编写Linux/Unix守护进程
- Linux守护进程的编程实现
- Linux守护进程的编程规则
- linux 守护进程
- linux 守护进程
- linux下的守护进程及会话、进程组
- LINUX 内核守护进程
- 【linux】守护进程
- Linux——守护进程(精灵进程)创建fork一次.两次的区别
- Linux多任务编程(七)---Linux守护进程及其基础实验
- Linux学习笔记之守护进程
- 深入理解Linux守护进程(ZT)
- Linux 守护进程出错处理
- Linux 下创建守护进程
- 在linux或者unix操作系统中在系统的引导的时候会开启很多服务,这些服务就叫做守护进程。守护进程是在后台运行不与任何控制终端关联,是Linux中的后台服务进程。它是一个生存期较长的进程,通常独立于
- linux守护进程
- Linux 守护进程的编程方法
- Linux 守护进程daemon
- Linux进程实践(5) --守护进程