1.守护进程只能存在一个;
2.由守护进程拉起服务程序,并wait;
3.当服务程序进程退出时,守护进程再次拉起服务程序,如此反复;
代码如下:
#include#include #include #include #include #define RUN_APP_PATH "./a.out"#define PARA_0 "start"#define PARA_1 ""#define SELF_APP_NAME "pup_daemon"int getProcessRunningCount(const char * pName){ FILE* fp = 0; int iCount = -1; char buf[1024] = {0}; char command[1024] = {0}; if(0 == pName) return -1; sprintf(command, "ps -C %s|wc -l", pName ); if((fp = popen(command,"r")) == NULL) { printf("[getProcessRunningCount] popen error ...... \r\n"); return -1; } if( (fgets(buf, 1024, fp)) != NULL ) { iCount = atoi(buf); } pclose(fp); return iCount;}int runDaemon(){ int iRunningCount = getProcessRunningCount(SELF_APP_NAME); printf("Running count is %d ... \r\n", iRunningCount); if(0 > iRunningCount) { printf("[getProcessRunningCount] err ... \r\n"); return 0; } if(2 < iRunningCount) { printf("App is already running ... \r\n"); return 0; } pid_t pid = -1; while(1) { pid = fork(); if (pid < 0) { fprintf(stderr, "error!"); usleep(1000 * 1000); continue; } else if( 0 == pid ) { if( 0 > execl(RUN_APP_PATH, PARA_0, PARA_1, (char*)0) ) { printf("execl err \r\n"); } printf("This is the child process! \r\n "); return 0; } else { printf("This is the parent process! child process id = %d \r\n", pid); } wait(0); usleep(1000 * 3000); } return 0;}int main(int argc, char ** argv ){ for(int i = 0; i < argc; ++i) { printf("para is %s \r\n", argv[i]); } runDaemon(); return 0;}