git » pymisc » commit 09219f0

In pcmp.Channel, detect broken pipes and raise an exception accordingly.

author Alberto Bertogli
2007-02-01 14:25:06 UTC
committer Alberto Bertogli
2007-02-01 14:25:06 UTC
parent 665d0b5ee42c2e376b2a8328b433f4631e704e15

In pcmp.Channel, detect broken pipes and raise an exception accordingly.

pcmp.py +20 -5

diff --git a/pcmp.py b/pcmp.py
index 4bf76a3..ada6be4 100644
--- a/pcmp.py
+++ b/pcmp.py
@@ -4,7 +4,7 @@ pcmp - Parent-Child Message Passing
 Alberto Bertogli (albertito@gmail.com)
 ------------------------------------------
 
-This module has only one class that implements a bidirectional channel, which
+This module implements a bidirectional channel with the Channel class, which
 allows you to send and receive python objects (as long as they're pickable)
 between a parent and its child.
 
@@ -12,12 +12,22 @@ 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().
 
+If the pipe gets broken (one of the processes closes the pipe or dies), send()
+and recv() will raise a BrokenPipe exception, defined here.
+
 It should work under any Unix, Windows and Mac systems.
 """
 
 import os
+import errno
 import pickle
 
+
+class BrokenPipe (Exception):
+	"Exception raised when the pipe gets broken."
+	pass
+
+
 class Channel (object):
 	"Parent-child message passing."
 
@@ -57,11 +67,16 @@ class Channel (object):
 
 	def send(self, o):
 		"Send an object."
-		pickle.dump(o, self._wfd, -1)
-		self._wfd.flush()
+		try:
+			pickle.dump(o, self._wfd, -1)
+			self._wfd.flush()
+		except IOError, errno.EPIPE:
+			raise BrokenPipe
 
 	def recv(self):
 		"Receive an object."
-		o = pickle.load(self._rfd)
-		return o
+		try:
+			return pickle.load(self._rfd)
+		except IOError, errno.EPIPE:
+			raise BrokenPipe