how to protect my process from being killed?

后端 未结 4 2040
故里飘歌
故里飘歌 2021-01-01 00:32

We have a mission-critical server program on top of Linux and we don\'t want others to terminate it accidentally. If somebody terminates it or it crashes, we want it to rest

4条回答
  •  礼貌的吻别
    2021-01-01 00:57

    You can restart your server from inside itself using fork. Oh the beauty of Unix.

    Something like:

    int result = fork();
    
    if(result == 0)
        DoServer();
    
    if(result < 0)
    {
        perror(); exit(1);
    }
    
    for(;;)
    {
        int status = 0;
        waitpid(-1, &status, 0);
        if(!WIFEXITED(status))
        {
            result = fork();
            if(result == 0)
                DoServer();
            if(result < 0)
            {
                puts("uh... crashed and cannot restart");
                exit(1);
            }
        }
        else exit(0);
    }
    

    EDIT:
    It's probably wise to use the WIFEXITED macro as test condition, which is more concise and portable (changed code accordingly). Plus, it fittingly models the semantics that we probably want.

    waitpid, given zero flags, won't return anything but either normal or abnormal termination. WIFEXITED results in true if the process exited normally, such as by returning from main or calling exit. If the process exited normally (e.g. because you requested that), one very probably does not want to keep restarting it until the end of days!

提交回复
热议问题