1.守護進程只能存在一個; code
2.由守護進程拉起服務程序,並wait; 進程
3.當服務程序進程退出時,守護進程再次拉起服務程序,如此反覆; get
代碼以下: it
#include<sys/types.h> #include<sys/wait.h> #include<unistd.h> #include<stdio.h> #include<stdlib.h> #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; }