C ++:外部应用程序调用超时 [英] C++: Timeout for an external application call

查看:161
本文介绍了C ++:外部应用程序调用超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于我正在使用的c ++程序,我必须调用一个外部应用程序来执行一些操作.我无法修改该应用程序.此操作可能会花费太多时间,因此我必须添加超时.我尝试使用system()和增强线程

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");
}

但是当我在10秒后返回主屏幕时,外部应用程序仍在后台运行. 使用exec()而不是system()无效,因为我丢失"了主机.我能做些什么? 我在Linux上.

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.

推荐答案

使用 fork(2) execve(2) waitpid(2)而不是system(其中在内部使用这些syscall).阅读高级Linux编程,其中介绍了 tricky 详细信息.

Use fork(2), execve(2), waitpid(2) instead of system (which internally uses these syscalls). Read Advanced Linux Programming which explains the tricky details.

您可能想在其中使用 setrlimit(2)这个孩子.或在父级 kill(2)中(第一个带有SIGTERM,然后在超时时使用SIGKILL).

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.

您可能希望孩子使用 setpgid( 2)setpgrp,然后使用 killpg(2).这将杀死孩子及其启动的任何命令(除非它们自己创建了自己的进程组).

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).

您可以处理SIGCHLD信号(请参见 signal(7) )使用 sigaction(2). SIGCHLD特别是在子进程终止时发送.

You could handle the SIGCHLD signal (see signal(7)) using sigaction(2). SIGCHLD would notably be sent when the child process terminates.

这篇关于C ++:外部应用程序调用超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆