Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better way to monitor and kill other program's stalled process in linux?

Tags:

c++

linux

I need my program to run some other program, but if the other program won't return within some time limit, I need to kill it. I came up with the following solution that seems to be working.

int main()
{
int retval, timeout=10;
pid_t proc1=fork();

if(proc1>0)
{
    while(timeout)
    {
        waitpid(proc1, &retval, WNOHANG);
        if(WIFEXITED(retval)) break; //normal termination
        sleep(1);
        --timeout;
        if(timeout==0)
        {
            printf("attempt to kill process\n");
            kill(proc1, SIGTERM);
            break;
        }
    }
}
else if(proc1==0)
{
    execlp("./someprogram", "./someprogram", "-a", "-b", NULL);
}
//else if fork failed etc.
return 0;
}

I need my program to be as robust as possible but I am new to programming under linux so I may not be aware of possible problems with it. My questions are: 1. Is this a proper solution to this particular problem or are there better methods? 2. Does anyone see possible problems or bugs that can lead to an unexpected behavior or a leak of system resources?

like image 773
vapid Avatar asked Oct 31 '22 09:10

vapid


1 Answers

(WIFEXITED(retval)) won't return true if the program is killed by a signal (including say a crash due to segmentation violation).

Probably best to just check for a successful return from waitpid. That will only happen if the program is terminated (whether voluntarily or not).

Depending on how important it is to make sure the process is gone...
After killing the process with SIGTERM, you could sleep another second or so and if it's still not gone, use SIGKILL to be sure.

like image 77
Gil Hamilton Avatar answered Nov 02 '22 11:11

Gil Hamilton