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

以下简单脚本在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)]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值