mpeterson
mpeterson

Reputation: 749

How to read from an os.pipe() without getting blocked?

I'm trying to read from an open os.pipe() to see if it's empty at the moment of the reading. The problem is that calling read() causes the program to block there until there is actually something to read there however there won't be any, if the test I'm doing succeeded.

I know I can use select.select() with a timeout however I wanted to know if there is another solution to the problem.

Upvotes: 11

Views: 8072

Answers (1)

vartec
vartec

Reputation: 134711

You might try this.

import os, fcntl
fcntl.fcntl(thePipe, fcntl.F_SETFL, os.O_NONBLOCK) 

With this thePipe.read() should be non-blocking.

From pipe(7) man page:

If a process attempts to read from an empty pipe, then read(2) will block until data is available. (...) Non-blocking I/O is possible by using the fcntl(2) F_SETFL operation to enable the O_NONBLOCK open file status flag.

Upvotes: 17

Related Questions