C++: Timeout for an external application call

时光总嘲笑我的痴心妄想 提交于 2019-12-24 15:24:20

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!