summaryrefslogtreecommitdiff
path: root/src/fifo.py
diff options
context:
space:
mode:
authorFlorent Le Coz <louiz@louiz.org>2011-11-09 01:26:54 +0100
committerFlorent Le Coz <louiz@louiz.org>2011-11-09 01:26:54 +0100
commit75ae1772e49a59b373c26d1c942f25edd473921c (patch)
tree65d8faee081db6c3800a48eff7007a4b626e4252 /src/fifo.py
parent8f02b6eb8e022ed1d34e0a0b0c7376eaf58acc32 (diff)
parent23d81901e7725bf67363113bc36a6e171bdb2033 (diff)
downloadpoezio-75ae1772e49a59b373c26d1c942f25edd473921c.tar.gz
poezio-75ae1772e49a59b373c26d1c942f25edd473921c.tar.bz2
poezio-75ae1772e49a59b373c26d1c942f25edd473921c.tar.xz
poezio-75ae1772e49a59b373c26d1c942f25edd473921c.zip
Merge branch 'master' of http://git.louiz.org/poezio
Diffstat (limited to 'src/fifo.py')
-rw-r--r--src/fifo.py70
1 files changed, 70 insertions, 0 deletions
diff --git a/src/fifo.py b/src/fifo.py
new file mode 100644
index 00000000..8306e24b
--- /dev/null
+++ b/src/fifo.py
@@ -0,0 +1,70 @@
+# Copyright 2011 Florent Le Coz <louiz@louiz.org>
+#
+# This file is part of Poezio.
+#
+# Poezio is free software: you can redistribute it and/or modify
+# it under the terms of the zlib license. See the COPYING file.
+
+"""
+Defines the Fifo class
+"""
+
+import logging
+log = logging.getLogger(__name__)
+
+import os
+import threading
+
+class OpenTrick(threading.Thread):
+ """
+ A threaded trick to make the open for writing succeed.
+ A fifo cannot be opened for writing if it has not been
+ yet opened by the other hand for reading.
+ So, we just open the fifo for reading and close it
+ immediately afterwards.
+ Once that is done, we can freely keep the fifo open for
+ writing and write things in it. The writing can fail if
+ there’s still nothing reading that fifo, but we just yell
+ an error in that case.
+ """
+ def __init__(self, path):
+ threading.Thread.__init__(self)
+ self.path = path
+
+ def run(self):
+ open(self.path, 'r').close()
+
+
+class Fifo(object):
+ """
+ Just a simple file handler, writing and reading in a fifo.
+ Mode is either 'r' or 'w', just like the mode for the open()
+ function.
+ """
+ def __init__(self, path, mode):
+ self.trick = None
+ if not os.path.exists(path):
+ os.mkfifo(path)
+ if mode == 'w':
+ self.trick = OpenTrick(path)
+ # that thread will wait until we open it for writing
+ self.trick.start()
+ self.fd = open(path, mode)
+
+ def write(self, data):
+ """
+ Try to write on the fifo. If that fails, this means
+ that nothing has that fifo opened, so the writing is useless,
+ so we just return (and display an error telling that, somewhere).
+ """
+ self.fd.write(data)
+ self.fd.flush()
+
+ def readline(self):
+ return self.fd.readline()
+
+ def __del__(self):
+ try:
+ self.fd.close()
+ except:
+ pass