Linux,子进程超时
好的,我需要编写一段调用脚本的代码,如果脚本中的操作挂起,则终止进程。
首选语言是 Python,但我也在查看 C 和 bash 脚本文档。
似乎是一个简单的问题,但我无法决定最好的解决方案。
迄今为止的研究:
- Python:虚拟机使用一些奇怪的线程模型 一次一个线程,行不通?
- C:到目前为止首选的解决方案似乎是使用SIGALARM + fork + 执行。但是 SIGALARM 不是堆安全的,所以它可以丢弃所有东西?
- Bash:超时程序?不是所有发行版的标准配置?
由于我是 Linux 的新手,我可能不知道这些功能有 500 个不同的陷阱,所以有人能告诉我什么是最安全和最干净的方法吗?
Ok, I need to write a code that calls a script, and if the operation in script hangs, terminates the process.
The preferred language is Python, but I'm also looking through C and bash script documentation too.
Seems like an easy problem, but I can't decide on the best solution.
From research so far:
- Python: Has some weird threading model where the virtual machine uses
one thread at a time, won't work? - C: The preferred solution so far seems to use SIGALARM + fork +
execl. But SIGALARM is not heap safe, so it can trash everything? - Bash: timeout program? Not standard on all distros?
Since I'm a newbie to Linux, I'm probably unaware of 500 different gotchas with those functions, so can anyone tell me what's the safest and cleanest way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
有一组 Python 代码具有完全可以完成此操作的功能,如果您了解 API,则不会有太大困难。
Pycopia 集合具有用于超时函数的调度程序模块,以及用于生成子进程和向其发送信号。在这种情况下可以使用
kill
方法。There is a collection of Python code that has features to do exactly this, and without too much difficulty if you know the APIs.
The Pycopia collection has the scheduler module for timing out functions, and the proctools module for spawning subprocesses and sending signals to it. The
kill
method can be used in this case.避免使用
SIGALRM
因为信号处理程序内部没有太多安全的事情可做。考虑到您应该使用的系统调用,在 C 中,在执行 fork-exec 启动子进程后,您可以定期调用
waitpid(2)
与WNOHANG
选项检查子进程是否仍在运行。如果waitpid
返回0
(进程仍在运行)并且所需的超时时间已过,您可以kill(2)
子进程。Avoid
SIGALRM
because there is not much safe stuff to do inside the signal handler.Considering the system calls that you should use, in C, after doing the fork-exec to start the subprocess, you can periodically call
waitpid(2)
with theWNOHANG
option to inspect whether the subprocess is still running. Ifwaitpid
returns0
(process is still running) and the desired timeout has passed, you cankill(2)
the subprocess.在 bash 中,您可以执行类似的操作:
示例:
您甚至可以尝试使用
trap 'script_stopped $pid' SIGCHLD
- 请参阅 bash man 以获取更多信息。更新:我发现其他命令超时。它完全满足您的需要 - 运行有时间限制的命令。示例:
10 秒后将终止
sleep
。In bash you can do something similar to this:
Example:
you can even try to use
trap 'script_stopped $pid' SIGCHLD
- see the bash man for more info.UPDATE: I found other command timeout. It does exactly what you need - runs a command with a time limit. Example:
will kill the
sleep
after 10 seconds.