author | Alberto Bertogli
<albertito@gmail.com> 2007-01-31 16:31:13 UTC |
committer | Alberto Bertogli
<albertito@gmail.com> 2007-01-31 16:31:13 UTC |
parent | 4d1641f324b1adb97493843ec37928a7921c0b8c |
pcmp.py | +47 | -0 |
samples/pcmp/sample1.py | +18 | -0 |
diff --git a/pcmp.py b/pcmp.py new file mode 100644 index 0000000..3c38c81 --- /dev/null +++ b/pcmp.py @@ -0,0 +1,47 @@ + +""" +This module implements a parent-child message passing. + +It has only one class that implements a bidirectional channel, which allows +you to send and receive python objects (as long as they're pickable) between a +parent and its child. + +You should instance it before you fork, and then call .child() or .parent() +according to your status. Then you can begin sending and receiving objects +with .send() and .recv(). + +It should work under any Unix, Windows and Mac systems. +""" + +import os +import pickle + +class Channel (object): + "Parent-child message passing." + + def __init__(self): + self._p2c = os.pipe() + self._c2p = os.pipe() + self._rfd = None + self._wfd = None + + def child(self): + "Tell the object we're the child." + self._wfd = os.fdopen(self._c2p[1], 'w') # we write via p1.w + self._rfd = os.fdopen(self._p2c[0], 'r') # and read via p2.r + + def parent(self): + "Tell the object we're the parent." + self._wfd = os.fdopen(self._p2c[1], 'w') # we write via p2.w + self._rfd = os.fdopen(self._c2p[0], 'r') # we read via p1.r + + def send(self, o): + "Send an object." + pickle.dump(o, self._wfd, -1) + self._wfd.flush() + + def recv(self): + "Receive an object." + o = pickle.load(self._rfd) + return o + diff --git a/samples/pcmp/sample1.py b/samples/pcmp/sample1.py new file mode 100644 index 0000000..8af08d9 --- /dev/null +++ b/samples/pcmp/sample1.py @@ -0,0 +1,18 @@ + +import os +import pcmp + +c = pcmp.Channel() + +pid = os.fork() +if pid == 0: + c.child() + c.send('Hola papi!') + print c.recv() +else: + c.parent() + c.send("Hola hijito!") + print c.recv() + os.wait() + +