问题
For a c++ program I'm working on, I have to call an external application to do some operations. I can't modify the application. This operations may take too much time so I have to add a timeout. I tried using system() and boost threads
int main()
{
[...]
boost::thread t(function1);
t.timed_join(boost::posix_time::seconds(10));
[...]
return 0;
}
void function1()
{
system("external application");
}
but when I return to the main 10 seconds later, the external application is still running in background. Using exec() instead of system() nothing works because I "lose" the main. What can I do? I'm on Linux.
回答1:
Use fork(2), execve(2), waitpid(2) instead of system
(which internally uses these syscalls). Read Advanced Linux Programming which explains the tricky details.
You could want to use setrlimit(2) in the child. Or in the parent kill(2) the child (first with SIGTERM
, then with SIGKILL
) on timeout.
You may want the child to make its own process group using setpgid(2) or setpgrp
, then kill the entire process group with killpg(2). This would kill both the child and any command it has started (unless these create there own process groups themselves).
You could handle the SIGCHLD
signal (see signal(7)) using sigaction(2). SIGCHLD
would notably be sent when the child process terminates.
回答2:
If you want to use exec you first have to fork a new process with does the actual exec
. Then after the timeout you can simply kill the child process. (And for the last you might want to read about signals.)
来源:https://stackoverflow.com/questions/18614263/c-timeout-for-an-external-application-call