3

I am currently reading Python 2.7's multiprocessing code. I am confused about the implementation of connection.Pipe.

It uses the following code to create a duplex pipe.

s1, s2 = socket.socketpair()
s1.setblocking(True)
s2.setblocking(True)
c1 = _multiprocessing.Connection(os.dup(s1.fileno()))
c2 = _multiprocessing.Connection(os.dup(s2.fileno()))
s1.close()
s2.close()

But why should we firstly dup s1 and s2's fileno and close them instead of using them directly?

I think it is quite different from the following implementation in C which close only parent on child process(and child on parent process) after fork is called.

calvin
  • 2,125
  • 2
  • 21
  • 38
  • The socket is for the two ends of the pipe to communicate with each other, not for the parent to communicate with either child. – chepner Mar 20 '20 at 12:29
  • 1
    Presumably, `s1.close()` will close the fd as a side effect (or, rather, part of its primary function.) `dup`ing the fd before closing `s1` is a lot cleaner than trying to surgically remove the closure of the fd from the `close` method. – William Pursell Mar 20 '20 at 13:36

0 Answers0