1. 程式人生 > >linux守護程序如何寫。

linux守護程序如何寫。

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <signal.h>
#include <sys/wait.h>

#include "common/hqdefine.h"
#include "utils/define.h"

#define PROGRAM_PATH_LENGTH_MAX 100
#define PROGRAM_NAME_LENGTH_MAX 50
#define PROGRAM_PARAM_LENGTH_MAX 10

bool run_ = true;

void signalFunc(int sig)
{
    run_ = false;
    printf("catch quit signal, destroy check_proc!\n");
}

void printUsage()
{
    printf("usage: ./check_proc program_name param1 param2 ...\n"
           "program_name the program to be guarded\n"
           "param1/2/... parameters passed tp the program\n");
}

int main(int argc, char *argv[])
{
    printf("check_proc program by xiefei 20181107_1\n");
    
    pid_t pid;
    pid_t ret;
    char programPath[PROGRAM_PATH_LENGTH_MAX];
    char programName[PROGRAM_NAME_LENGTH_MAX];
    char *programParam[PROGRAM_PARAM_LENGTH_MAX];
    
    signal(SIGINT, signalFunc);
    
    if (argc < 2) {
        printUsage();
        return -1;
    }
    
    bzero(programPath, sizeof(programPath));
    bzero(programName, sizeof(programName));
    bzero(programParam, sizeof(programParam));
    
    //判斷程式名中是否含有'/'字元
    if (NULL == strchr(argv[1], '/')) {
        strcat(programPath, "./");
        strcat(programPath, argv[1]);
        strcpy(programName, argv[1]);
    } else {
        strcpy(programPath, argv[1]);
        char *lastChar = strrchr(programPath, '/');
        sprintf(programName, "%s", (lastChar + 1));
    }
    
    programParam[0] = programName;
    for (int i = 2; i < argc; i ++) {
        programParam[i-1] = argv[i];
    }
    programParam[argc] = NULL;
    
    while (run_) {
        pid = fork();
        if (pid < 0) {
            sleep(1);
        } else if (0 == pid) {
            //child
            execv(programPath, programParam);
        } else {
            //parent
            int status = 0;
            ret = waitpid(pid, &status, 0);
            if (WIFSTOPPED(status)) {
                kill(pid, SIGKILL);
            }
        }
        
        sleep(1);
    }
    
    return 0;
}