Process to process synchronization (unix)

Eric Brunel eric.brunel at pragmadev.com
Wed Mar 20 11:01:12 EST 2002


Gillou wrote:
> I need to learn those named pipes.
> Are there pythonic examples somewhere ?

Here are an awfully simple example of two scripts speaking to each other. 
The principle is that the first run creates the named pipe if it doesn't 
already exist, then opens it and tries either to write something to it, or 
to read something from it. Here are the two scripts:

-- Writing script --------------
import os

pipeName = 'np.pipe'

## If named pipe does not exist, create it
if not os.path.exists(pipeName):
  os.mkfifo(pipeName)

## Open pipe and say something through it
print "Opening"
p = open(pipeName, 'w')
print "Sending..."
p.write("Wot?")
## Over
print "Done."
p.close()
print "Closed."
---------------------------

-- Reading script --------------
import os

pipeName = 'np.pipe'

## If named pipe does not exist, create it
if not os.path.exists(pipeName):
  os.mkfifo(pipeName)

## Open pipe and try to read something from it
print "Opening"
p = open(pipeName, 'r')
print "Reading..."
s = p.read()
## Over
print "Received %s" % s
p.close()
print "Closed."
---------------------------

So the important function here is os.mkfifo, creating the named pipe. It 
just creates a pseudo-file in the current directory, which can be opened 
like any other file. But trying to read from it will block until there is 
some other process writing to it, and the same in reverse: writing is 
blocking until someone reads at the other end.

Try the two scripts: you must run them as 2 different processes (in 2 
different xterms, for example). You may start whichever you want first: it 
will stop, and resume execution only when the other one is started. You may 
also try to add some time.sleep between the opening and/or reading and see 
what happens.

HTH. Good luck!
 - eric -




More information about the Python-list mailing list