Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python "Bad file descriptor" when reading from pipe

I'm trying to start a subprocess and pass a pipe file descriptor to it to read from. However when I try to read from the pipe in the child process I get "Bad file descriptor", even though I can read from the pipe in the parent process just fine.

Here's the parent process:

import subprocess
import sys
import os

r, w = os.pipe()

os.set_inheritable(r, True)

p = subprocess.Popen(["python3", "client.py", str(r)])

os.write(w, b"hello")

p.wait()

And here's the child process:

import sys
import os

r = int(sys.argv[1])
print("[Client]", os.read(r,  5))

Any help would be much appreciated.

like image 887
kasra Avatar asked Sep 14 '26 13:09

kasra


1 Answers

From the official Python docs:

Using the subprocess module, all file descriptors except standard streams are closed, and inheritable handles are only inherited if the close_fds parameter is False.

like image 50
Amos Baker Avatar answered Sep 17 '26 01:09

Amos Baker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!