python - os.open():没有这样的设备或地址?

时间:2011-08-04 11:06:48

标签: python

我想尝试命名管道,所以我下载了一段代码并对其进行了修改以测试:

fifoname = '/home/foo/pipefifo'                       # must open same name

def child( ):
    pipeout = os.open(fifoname, os.O_NONBLOCK|os.O_WRONLY)  
    # open fifo pipe file as fd
    zzz = 0
    while 1:
        time.sleep(zzz)
        os.write(pipeout, 'Spam %03d\n' % zzz)
        zzz = (zzz+1) % 5

def parent( ):
    pipein = open(fifoname, 'r')                 # open fifo as stdio object
    while 1:
        line = pipein.readline( )[:-1]            # blocks until data sent
        print 'Parent %d got "%s" at %s' % (os.getpid(), line, time.time( ))

if __name__ == '__main__':
    if not os.path.exists(fifoname):
        os.mkfifo(fifoname)                       # create a named pipe file
    if len(sys.argv) == 1:
        parent( )                                 # run as parent if no args
    else:
          child() 

我尝试运行脚本,它返回此错误:

pipeout = os.open(fifoname, os.O_NONBLOCK|os.O_WRONLY)     # open fifo pipe file as fd
OSError: [Errno 6] No such device or address: '/home/carrier24sg/pipefifo'

导致此错误的原因是什么? (我在Linux中运行python 2.6.5)

2 个答案:

答案 0 :(得分:9)

来自man 7 fifo

  

进程可以在非阻塞模式下打开FIFO。在这种情况下,即使在写入端没有打开任何人,打开以进行只读也会成功,只有写入才会打开ENXIO(没有这样的设备或地址),除非另一端已经打开

所以你收到这个令人困惑的错误信息,因为你试图打开一个命名管道进行阅读,而你正试图用非阻塞open(2)来打开它。

在您的具体示例中,如果您在child()之前运行parent(),则会发生此错误。

答案 1 :(得分:0)

这对我在linux上工作:

import time
import os, sys
fifoname = '/tmp/pipefifo'  # must open same name

def child( ):
    pipeout = os.open(fifoname, os.O_NONBLOCK|os.O_WRONLY)     # open fifo pipe file as fd
    zzz = 0
    while 1:
        time.sleep(zzz)
        os.write(pipeout, 'Spam %03d\n' % zzz)
        zzz = (zzz+1) % 5

def parent( ):
   pipein = open(fifoname, 'r')   # open fifo as stdio object
   while 1:
     line = pipein.readline( )[:-1]    # blocks until data sent
     print 'Parent %d got "%s" at %s' % (os.getpid(), line, time.time( ))

if __name__ == '__main__':
   if not os.path.exists(fifoname):
     os.mkfifo(fifoname)                       # create a named pipe file
   if len(sys.argv) == 1:
       parent( )                                 # run as parent if no args
   else:
       child()

我认为问题取决于平台,你在哪个平台? o可能是一些权限问题。