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?
vapid source share