Linux,在子进程上超时(Linux, timing out on subprocess)

好吧,我需要编写一个调用脚本的代码,如果脚本中的操作挂起,则终止该过程。

首选语言是Python,但我也在查看C和bash脚本文档。

似乎是一个简单的问题,但我无法决定最佳解决方案。

从目前为止的研究:

Python:有一些奇怪的线程模型,其中虚拟机一次只使用一个线程,不起作用?

C:到目前为止,首选的解决方案似乎是使用SIGALARM + fork + execl。 但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?

原文:https://stackoverflow.com/questions/7244145

更新时间:2020-02-02 22:01

最满意答案

在bash中你可以做类似的事情:

用&启动后台脚本/程序

获取后台进程的进程ID

睡了一段时间

然后杀死进程(如果它已经完成你不能杀死它)或者你可以检查进程是否仍然存在然后杀死它。

例:

sh long_time_script.sh &

pid=$!

sleep 30s

kill $pid

你甚至可以尝试使用trap 'script_stopped $pid' SIGCHLD - 请参阅bash man获取更多信息。

更新:我发现其他命令超时 。 它完全符合您的需要 - 运行带有时间限制的命令。 例:

timeout 10s sleep 15s

将在10秒后杀死sleep 。

In bash you can do something similar to this:

start the script/program in background with &

get the process id of the background process

sleep for some time

and then kill the process (if it is finished you cannot kill it) or you can check if the process is still live and then to kill it.

Example:

sh long_time_script.sh &

pid=$!

sleep 30s

kill $pid

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:

timeout 10s sleep 15s

will kill the sleep after 10 seconds.

2011-08-31

相关问答

自从工作了就好久没发博客,还是出来冒个泡=。= 前段时间写的一个项目需要用python的subprocess.Popen大量调用某shell命令,运行到一定量级之后就会产生内存溢出,造成大量线程阻塞,然后就会造成([Errno 24] Too many open files)这个异常。 网上有人说是close_fds=True这个参数在python2.x默认没打开,这个参数可以关闭文件描述符,试了没有作用。 后来在国外某个人的帖子找到了和我类似的问题,解决办法就是执行后把stdin,stdout,

...

问题是export不是实际的命令或文件。 它是一个内置命令,像bash和sh这样的shell,所以当你尝试一个subprocess.Popen你会得到一个异常,因为它找不到export命令。 默认情况下, os.execvp()执行一个os.execvp()来产生一个新的进程,这将不允许你使用shell内部函数。 你可以做这样的事情,但你必须改变你的电话给Popen 。 http://docs.python.org/library/subprocess.html 您可以指定shell=True使其

...

在Python 3.3+中: from subprocess import STDOUT, check_output

output = check_output(cmd, stderr=STDOUT, timeout=seconds)

output是包含命令的合并stdout,stderr数据的字节串。 不同于proc.communicate()方法,该代码会在问题文本中指定的非零退出状态引发CalledProcessError 。 我删除了shell=True因为它经常被不必要地使用。 如果

...

所以,事实证明,我在复制之前锁定了表,并且由于副本在不同的进程中运行,所以它看到一个锁定的表可以写入并挂起。 So, it turns out that I was locking the table prior to the copy, and since the copy runs in a different process, it was seeing a locked table to write to and hanging.

commands产生一个执行glob扩展的shell。 除非你传递shell = True否则subprocess不会生成一个shell。 换一种说法: p=subprocess.Popen("ls *00080",shell=True,stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

应该做与commands相同的事情。 commands spaws a shell which does the glob expansion. subproce

...

根据你的代码,唯一“不起作用”的事实是死链接导致它抛出一个OSError 。 我已将其修改为以下内容: #!/usr/bin/env python

import os

import time

import datetime

dirpath = "./"

for p, ds, fs in os.walk(dirpath):

for fn in fs:

filepath = os.path.join(p, fn)

# This catches bad li

...

在bash中你可以做类似的事情: 用&启动后台脚本/程序 获取后台进程的进程ID 睡了一段时间 然后杀死进程(如果它已经完成你不能杀死它)或者你可以检查进程是否仍然存在然后杀死它。 例: sh long_time_script.sh &

pid=$!

sleep 30s

kill $pid

你甚至可以尝试使用trap 'script_stopped $pid' SIGCHLD - 请参阅bash man获取更多信息。 更新:我发现其他命令超时 。 它完全符合您的需要 - 运行带有时间限制的命令。

...

为什么使用grep? 为什么不用Python做所有的东西? from subprocess import Popen, PIPE

p = Popen(['ping', 'google.com'], shell=False, stdin=PIPE, stdout=PIPE)

for line in p.stdout:

if 'timeout' in line.split():

# Process the error

print("Timeout error!

...

这是挂钟时间( real ),而不是在用户空间( user )或内核( system )中花费的时间。 您可以通过运行诸如sleep 60类的过程来自行测试,该过程几乎不使用任何用户或系统时间,并观察它仍然超时。 This is wall-clock time (real), not time spent in either userland (user) or the kernel (system). You can test this yourself by running a process

...

您应该能够捕获TimeoutExpired execption并忽略它 try:

cmd = subprocess.check_output([os.path.dirname(sys.argv[0])+ SCRIPT], stdin=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=1)

except subprocess.CalledProcessError e:

print(e)

except subprocess.T

...

查看linux进程超时,Linux,在子进程上超时(Linux, timing out on subprocess)相关推荐

  1. 【Linux进程、线程、任务调度】一 Linux进程生命周期 僵尸进程的含义 停止状态与作业控制 内存泄漏的真实含义 task_struct以及task_struct之间的关系

    学习交流加(可免费帮忙下载CSDN资源): 个人微信: liu1126137994 学习交流资源分享qq群1(已满): 962535112 学习交流资源分享qq群2: 780902027 文章目录 1 ...

  2. 观察Linux进程 线程的异步并发执行,操作系统linux版实验报告.doc

    操作系统linux版实验报告.doc (29页) 本资源提供全文预览,点击全文预览即可全文预览,如果喜欢文档就下载吧,查找使用更方便哦! 19.90 积分 操作系统实验报告(Linux版)网络142 ...

  3. 北京linux嵌入式培训,北京嵌入式培训上嵌Linux开发基础和嵌入式C语言初级编程总结...

    该楼层疑似违规已被系统折叠 隐藏此楼查看此楼 说到学习Linux开发基础,有一样是不得不说,而且Llinux系统中最常用也最有用的东西,那就是各种命令.虽然Linux桌面应用发展很快,但是命 令在Li ...

  4. zedboard运行linux,Zedboard使用II——在Zedboard上运行Linux

    8种机械键盘轴体对比 本人程序员,要买一个写代码的键盘,请问红轴和茶轴怎么选? Xillinux是一个支持在Zedboard.ZyBo.SocKit板子上运行的包括软件和FPGA代码的图形化桌面Lin ...

  5. 操作系统实验报告linux进程管理,计算机操作系统实验报告三Linux进程基本管理.doc...

    GDOU-B-11-112广东海洋大学学生实验报告书(学生用表) GDOU-B-11-112 实验名称 Linux进程基本管理 课程名称 计算机操作系统 课程号 学院(系) 专业 统 班级 学生姓名 ...

  6. surface pro linux服务器,Surface Pro平板电脑上安装Linux / Ubuntu的技巧

    嗯,Windows 10和Windows 8.1在Surface Pro上运行顺畅,但我认为有些用户想知道如何以及他们是否可以在上安装任何其他操作系统.您会很高兴听到答案是'是'.您始终可以将操作系统 ...

  7. linux 版本号 笔记本_在笔记本电脑上安装Linux完全版

    当前,笔记本电脑越来越多地成为工程师.技术人员的标准 办公配置.随着Linux操作系统影响的逐步深入,许许多多的Linux使用者希望能够在自己的笔记本电脑上运行Linux操作系统,以便随时随地地使用. ...

  8. linux进程管理之mm_struct,【转】Linux进程管理之SMP负载平衡(续二)

    继续来分析balance_tasks()函数,结合代码中的注释,理解这段代码应该很容易,在这里主要分析它的两个重要的子函数,即can_migrate_task()和pull_task(). 先来看ca ...

  9. linux用vfork创建进程,[Linux进程]使用vfork创建子进程并且执行命令

    /*这是一个其分别利用子进程和父进程对一个count进行计数并且输出, 用于展示父进程和子进程是共享一个数据段*/ #include #include #include #include int ma ...

最新文章

  1. spring 判断非空提示断言
  2. img 光盘映像文件已损坏_系统封装||还在用MSDN下载Windows镜像文件?你out了,用这个就可以了...
  3. Parameter 对象
  4. 解决安装ROS 时rosdep update 问题(time out)
  5. x265-创建encdata
  6. 【LeetCode】461. Hamming Distance (java实现)
  7. [Python] np.nonzero(ndarray) 返回数组中不为0的元素的索引
  8. 9.Memcached 介绍
  9. 39-java 输入输出总结
  10. python坐标系教程_python Shapely使用指南详解
  11. 多网卡下同网段内所有网卡共用一个IP的问题分析
  12. C# Newtonsoft的使用
  13. 高考志愿填报|物联网为何成为【热门选手】?
  14. ec----------
  15. 838计算机考研用书,河海计算机838考研大纲(5页)-原创力文档
  16. 0基础学Python第四天:Python3的基础语法
  17. postgresql 12.0 源码编译安装
  18. css元素旋转原点,使用transform-origin属性改变元素变换原点
  19. ZIGBEE------协调器断开重连,终端设备无法重新入网。
  20. Docker搭建持续集成平台Jenkins

热门文章

  1. 一起来飞车服务器维护到什么时候,《一起来飞车2》更新维护公告
  2. invader的java学习第一天基础篇
  3. 【Mr幺幺肆】Nero Burning ROM刻录时报错could not perform start of disc-at-once的解决方法
  4. zzuli OJ 1006: 求等差数列的和
  5. Three.js高光贴图(.specularMap)
  6. mgre 多点通用路由封装协议 hub-spoke
  7. Linux高级文本编辑器比较:kate vs gedit
  8. 再推荐一款即时通讯聊天app源码
  9. 二次拟合r方_拟合R语言中的多项式回归
  10. 制动器作用停止 发那科机器人_发那科机器人报警处理(中文)