os.pipe() + os.fork()

Discussion in 'Python' started by Sebastian Noack, Feb 20, 2010.

  1. Hi,

    I have a problem using os.pipe() together with os.fork(). Usually when
    the writing end of the pipe is closed, the reading end gets EOF. So
    subsequent attempts to read data will return an empty string. But when
    you call os.fork() after you have created a pipe using os.pipe(), and
    read data from the pipe in the child process, when the partent process
    has already closed the writing end, the reading end does not get EOF.
    Instead of the os.read() call in the child process is blocking.

    I am using Linux, so I would like to know if this is a bug in Python or
    just weird behaviour under Linux and if it is possible work around it.

    Regards
    Sebastian Noack


    ---------------------------------------------------------------------------

    import os

    def test_pipe_sync():
    pipe = os.pipe()

    os.write(pipe[1], 'Spam')
    os.close(pipe[1])

    print repr(os.read(pipe[0], 4)) # 'Spam' is printed.
    print repr(os.read(pipe[0], 4)) # '' is printed, because of EOF is reached.

    def test_pipe_forked():
    pipe = os.pipe()
    pid = os.fork()

    if pid:
    os.write(pipe[1], 'Spam')
    os.close(pipe[1])

    os.waitpid(pid, 0)
    else:
    print repr(os.read(pipe[0], 4)) # 'Spam' is printed.
    print repr(os.read(pipe[0], 4)) # Nothing is printed and os.read()
    # is blocking, eventhough the other
    # end of the pipe was closed.

    if __name__ == '__main__':
    test_pipe_sync()

    print
    print '-' * 80
    print

    test_pipe_forked()

    -----BEGIN PGP SIGNATURE-----
    Version: GnuPG v1.4.9 (GNU/Linux)

    iEYEARECAAYFAkt/uxQACgkQhef27Il4mhh9EACeJ//Khqb0fnjh3z5Qq6iXaMVY
    eEsAoOupjftyGBAnn7DSGlHZhOukVrGl
    =F59I
    -----END PGP SIGNATURE-----
    Sebastian Noack, Feb 20, 2010
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Hoegje
    Replies:
    2
    Views:
    22,536
    Gianni Mariani
    Dec 5, 2003
  2. PC

    pipe() dup2() fork() execl() select()

    PC, Aug 9, 2003, in forum: C Programming
    Replies:
    3
    Views:
    1,252
  3. Rafael Giannetti Viotti

    Subprocess and pipe-fork-exec primitive

    Rafael Giannetti Viotti, Jul 30, 2007, in forum: Python
    Replies:
    2
    Views:
    3,006
    Rafael V.
    Aug 1, 2007
  4. Eric Snow

    os.fork and pty.fork

    Eric Snow, Jan 8, 2009, in forum: Python
    Replies:
    0
    Views:
    571
    Eric Snow
    Jan 8, 2009
  5. Gary Herron

    Re: os.pipe() + os.fork()

    Gary Herron, Feb 20, 2010, in forum: Python
    Replies:
    2
    Views:
    277
Loading...

Share This Page