背景
我有两个python进程需要相互通信。comminication由名为Pipe的类处理。我为此创建了一个单独的类,因为需要传递的大多数信息都是以字典的形式出现的,所以Pipe实现了一个非常简单的协议来完成这项工作。
以下是管道构造函数:
def __init__(self,sPath):
"""
create the fifo. if it already exists just associate with it
"""
self.sPath = sPath
if not os.path.exists(sPath):
try:
os.mkfifo(sPath)
except:
raise Exception('cannot mkfifo at path \n {0}'.format(sPath))
self.iFH = os.open(sPath,os.O_RDWR | os.O_NONBLOCK)
self.iFHBlocking = os.open(sPath,os.O_RDWR)
所以理想情况下,我只需要在每个进程中用相同的路径构建一个管道,他们就能很好地交谈。
我将略过关于协议的内容,因为我认为这里基本上没有必要。
所有读写操作都使用以下“基本”函数:
def base_read_blocking(self,iLen):
self.lock()
lBytes = os.read(self.iFHBlocking,iLen)
self.unlock()
return lBytes
def base_read(self,iLen):
print('entering base read')
self.lock()
lBytes = os.read(self.iFH,iLen)
self.unlock()
print('exiting base read')
return lBytes
def base_write_blocking(self,lBytes):
self.lock()
safe_write(self.iFHBlocking,lBytes)
self.unlock()
def base_write(self,lBytes):
print('entering base write')
self.lock()
safe_write(self.iFH,lBytes)
self.unlock()
print('exiting base write')
在另一篇文章中建议安全写作
def safe_write(*args, **kwargs):
while True:
try:
return os.write(*args, **kwargs)
except OSError as e:
if e.errno == 35:
import time
print(".")
time.sleep(0.5)
else:
raise
锁定和解锁的处理方式如下:
def lock(self):
print('locking...')
while True:
try:
os.mkdir(self.get_lock_dir())
print('...locked')
return
except OSError as e:
if e.errno != 17:
raise e
def unlock(self):
try:
os.rmdir(self.get_lock_dir())
except OSError as e:
if e.errno != 2:
raise e
print('unlocked')
问题
有时会发生这种情况:
....in base_read
lBytes = os.read(self.iFH,iLen)
OSError: [Errno 11] Resource temporarily unavailable
有时候很好。
神奇的解决方案
我似乎阻止了这个问题的发生。请注意,这不是我回答自己的问题。下一节将解释我的问题。
我把read函数改成更像这样,然后它整理出:
def base_read(self,iLen):
while not self.ready_for_reading():
import time
print('.')
time.sleep(0.5)
lBytes = ''.encode('utf-8')
while len(lBytes)<iLen:
self.lock()
try:
lBytes += os.read(self.iFH,iLen)
except OSError as e:
if e.errno == 11:
import time
print('.')
time.sleep(0.5)
finally:
self.unlock()
return lBytes
def ready_for_reading(self):
lR,lW,lX = select.select([self.iFH,],[],[],self.iTimeout)
if not lR:
return False
lR,lW,lX = select.select([self.iFHBlocking],[],[],self.iTimeout)
if not lR:
return False
return True
问题
我正在努力弄清楚它为什么暂时不可用。由于锁定机制,这两个进程无法同时访问实际命名的管道(除非我弄错了?)那么这是不是因为我的程序没有考虑到fifos的一些更基本的因素?
我只想要一个解释。。。我找到的解决方案是有效的,但看起来很神奇。有人能解释一下吗?
系统
我以前有一个similar problem with Java。看看公认的答案——问题是我在循环中创建新线程。我建议您查看创建管道的代码,并确保您没有创建多个管道。
相关问题 更多 >
编程相关推荐