0

I have this test.py :

#!/usr/bin/env python3
import os
import sys
from select import select
from subprocess import Popen, PIPE

with Popen(('bash', '-c', 'echo 1; sleep 1; echo 2'), stdout=PIPE) as p:
    readable = { p.stdout.fileno(): sys.stdout.buffer }
    while readable:
        fds = select(readable, [], [], 0.1)
        print(f"readable is True. fds = {fds}")
        if not fds[0]: continue
        for fd in fds[0]:
            print("In for loop")
            data = os.read(fd, 1024) # read available
            if not data: # EOF
                print(f"delelting {fd}")
                del readable[fd]
            else: 
                readable[fd].write(data)
                readable[fd].flush()
                p.kill()

When I run it, I got this :

~/tmp$ ./test.py
readable is True. fds = ([4], [], [])
In for loop
1
readable is True. fds = ([4], [], [])
In for loop
delelting 4
~/tmp$

This is what I expected. But somtimes I got this by running the same script :

~/tmp$ ./test.py
readable is True. fds = ([4], [], [])
In for loop
1
readable is True. fds = ([], [], [])
readable is True. fds = ([], [], [])
readable is True. fds = ([], [], [])
readable is True. fds = ([], [], [])
readable is True. fds = ([], [], [])
readable is True. fds = ([], [], [])
readable is True. fds = ([], [], [])
readable is True. fds = ([], [], [])
readable is True. fds = ([], [], [])
readable is True. fds = ([], [], [])
readable is True. fds = ([4], [], [])
In for loop
delelting 4
~/tmp$

I'm using Python 3.8.2/ubuntu

Philippe
  • 20,025
  • 2
  • 23
  • 32
  • I'd guess this statement is at fault: ` if not fds[0]: continue` - check if I'm right by adding some diagnostic print within this if's body. – Błotosmętek Jul 10 '20 at 21:27
  • @Błotosmętek Updated, I don't think `if not fds[0]: continue` is the problem. – Philippe Jul 10 '20 at 21:35
  • Signaling a shell does not guarantee that the signal will be forwarded to its children. If you extend this into a real-world use case where there are non-builtin commands invoked, you'll see quite different behavior. – Charles Duffy Aug 07 '21 at 22:32

0 Answers0