Best way to control and kill other running processes on Linux?

I need my program to run some other program, but if the other program does not return for some time, I need to kill it. I came up with the following solution that seems to work.

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 as reliable as possible, but I am new to Linux programming, so I may not know about possible problems with it. My questions are: 1. Is this the right solution to this particular problem or are there better methods? 2. Does anyone see possible problems or errors that could lead to unexpected behavior or leakage of system resources?

+5
source share
1 answer

(WIFEXITED(retval)) will not return true if the program was killed by a signal (including, for example, a failure due to segmentation violation).

It is probably best to just check for a successful return from waitpid . This will happen only if the program is completed (voluntarily or not).

Depending on how important it is to make sure the process is gone ...
After you killed the process with SIGTERM , you could sleep another second or so, and if it still hasn't disappeared, use SIGKILL to make sure.

+2
source

Source: https://habr.com/ru/post/1242711/


All Articles