在Python中使用linux的命名管道,pythonlinux,在Python中使用li


在Python中使用linux的命名管道

管道是一种简单的FIFO通信信道,它是单向通信的。 通常启动进程创建一个管道,然后这个进程创建一个或者多个进程子进程接受管道信息,由于管道是单向通信,所以经常需要创建两个管道来实现双向通信。

在Linux中,通过使用系统的管道调用来创建管道,系统会创建一对文件,一个用来读(接受),另一个用来写(sender),在shell中我们可以通常使用|来创建管道

命名管道是对传统管道的扩展,默认的管道是匿名管道,只在程序运行时存在;而命名管道是持久化的,当不需要时需要删除它。

命名管道使用文件系统,由mkfifo()方法创建。一旦创建了,两个独立的进程都可以访问它,一个读,另外一个写。

命名管道支持阻塞读和阻塞写操作: 如果一个进程打开文件读,它会阻塞直到另外一个进程写。 但是我们可以指定O_NONBLOCK选项来启用非阻塞模式。

命名管道必须以只读或者只写的模式打开,它不能以读+写的模式打开,因为它时单向通信。如果要实现双向通信,必须打开两个命名管道。

下面是一个python使用命名管道做同步通信的例子

pipe_test_1.py

#!/usr/bin/pythonimport cPickleimport os#communicate with another process through named pipe#one for receive command, the other for send commandwfPath = "./p1"rfPath = "./p2"wp = open(wfPath, 'w')wp.write("P1: How are you?")        wp.close()rp = open(rfPath, 'r')response = rp.read()print "P1 hear %s" % responserp.close()wp = open(wfPath, 'w')wp.write("P1: I'm fine too.")       wp.close()

pipe_test_2.py

#!/usr/bin/pythonimport cPickleimport os#communicate with another process through named pipe#one for receive command, the other for send commandrfPath = "./p1"wfPath = "./p2"try:    os.mkfifo(wfPath)    os.mkfifo(rfPath)except OSError:    passrp = open(rfPath, 'r')response = rp.read()print "P2 hear %s" % responserp.close()wp = open(wfPath, 'w')wp.write("P2: I'm fine, thank you! And you?")       wp.close()rp = open(rfPath, 'r')response = rp.read()print "P2 hear %s" % responserp.close()

运行上面的例子代码需要:

打开一个终端, 运行 pipe_test_2.py启动另一个终端,运行pipe_test_1.py

需要注意要先执行pipe_test_2.py 否则会报错,打不开管道。

评论关闭