'EOF or blocking when dealing with the pipe

Usually, when creating pipes for IPC between parent and child processes, we immediately closed the read fd in parent process and write fd in the child process. I don't understand why the read behavior is different for parent if we don't close the child write fd.

First case: (the write fd in child process is not closed),'Blocking' is never printed and the os.read is blocking indefinitely.

import os

r,w = os.pipe()
pid = os.fork()

if pid:
    print('parent %s'%pid)
else:
    print('child %s'%pid)
    # os.close(w) without this line, os.read would block
    num = os.read(r, 100)
    print('Blocking')
    print(num)

Second case: (the write fd in child process is closed), 'Blocking' is printed and EOF is reached.

import os

r,w = os.pipe()
pid = os.fork()

if pid:
    print('parent %s'%pid)
else:
    print('child %s'%pid)
    os.close(w) 
    num = os.read(r, 100)
    print('Blocking')
    print(num)


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source