linux popen线程安全,是subprocess.Popen不是线程安全的吗?

该博客讨论了一个Python脚本在使用subprocess.Popen时遇到的间歇性挂起问题,这个问题在启用线程锁后得到解决。脚本涉及多线程调用shell脚本来计算阶乘,并在计算过程中可能出现阻塞。通过使用线程锁,确保了子进程的线程安全性,从而避免了挂起现象。
摘要由CSDN通过智能技术生成

以下简单脚本在subprocess.Popen间歇性地挂起(大约30%的时间).

除非use_lock = True,然后它永远不会挂起,导致我相信子进程不是线程安全的!预期的行为是脚本在5-6秒内完成.

为了演示这个bug,只需运行几次"python bugProof.py"直到它挂起.Ctrl-C退出.你会看到'后Popen'只出现一次或两次,但不是第三次出现.

import subprocess, threading, fcntl, os, time

end_time = time.time()+5

lock = threading.Lock()

use_lock = False

path_to_factorial = os.path.join(os.path.dirname(os.path.realpath(__file__)),'factorial.sh')

def testFunction():

print threading.current_thread().name, '| pre-Popen'

if use_lock: lock.acquire()

p = subprocess.Popen([path_to_factorial], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

if use_lock: lock.release()

print threading.current_thread().name, '| post-Popen'

fcntl.fcntl(p.stdout, fcntl.F_SETFL, os.O_NONBLOCK)

fcntl.fcntl(p.stderr, fcntl.F_SETFL, os.O_NONBLOCK)

while time.time()

try: p.stdout.read()

except: pass

try: p.stderr.read()

except: pass

print threading.current_thread().name, '| DONE'

for i in range(3):

threading.Thread(target=testFunction).start()

上面引用的shell脚本(factorial.sh):

#!/bin/sh

echo "Calculating factorial (anything that's somewhat compute intensive, this script takes 3 sec on my machine"

ans=1

counter=0

fact=999

while [ $fact -ne $counter ]

do

counter=`expr $counter + 1`

ans=`expr $ans \* $counter`

done

echo "Factorial calculation done"

read -p "Test input (this part is critical for bug to occur): " buf

echo "$buf"

系统信息:Linux 2.6.32-358.123.2.openstack.el6.x86_64#1 SMP Thu Sep 26 17:14:58 EDT 2013 x86_64 x86_64 x86_64 GNU/Linux

Python 2.7.3(默认,2013年1月22日,11:34 :30)

[linux2上的[GCC 4.4.6 20120305(Red Hat 4.4.6-4)]

关于 subprocess.Popen 的超时问题,实际上 subprocess.Popen 本身并没有内置的超时机制。它只是用于启动和控制子进程的类,不会主动监测子进程的执行时间。 如果你希望在子进程执行超时后进行相应处理,可以使用 subprocess.Popen 实例的 communicate 方法结合 threading 模块来实现超时控制。具体步骤如下: 1. 创建一个线程,在指定时间后终止子进程的执行。 2. 在主线程中调用 subprocess.Popen 实例的 communicate 方法,该方法会阻塞直到子进程执行完毕或超时终止。 下面是一个示例代码,其中设置了超时时间为 10 秒: ```python import subprocess import threading def run_command(command): proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) timer = threading.Timer(10, proc.kill) # 设置超时时间为 10 秒 try: timer.start() stdout, stderr = proc.communicate() finally: timer.cancel() return stdout, stderr # 调用示例 command = ['your_command', 'arg1', 'arg2'] stdout, stderr = run_command(command) ``` 在这个示例中,我们创建了一个 run_command 函数来执行子进程,并通过 threading.Timer 设置了超时时间为 10 秒。当超时时间到达后,会调用 proc.kill 方法终止子进程的执行。最后使用 proc.communicate 方法获取子进程的输出。 需要注意的是,子进程的执行时间可能会受到多个因素的影响,如所执行的命令复杂度、计算资源的负载等等。因此,具体的超时时间应根据实际情况进行调整。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值