I am studying for the PHP 5 Certification exam. This function was mentioned in the practice exams.
function stream_set_blocking():
Sets blocking or non-blocking mode on a stream.
This function works for any stream that supports non-blocking mode (currently, regular files and socket streams).
From both a high-level and low-level perspective, how do blocking mode and non-blocking mode streams behave in PHP? What i a socket stream and a non-socket stream? Examples are appreciated.
So, yeah, PHP is blocking, so using a timeout with a function was out of the question. There are a number of workarounds, but they're not very robust. But then I remembered Amp. Amp (and ReactPHP) are frameworks for asynchronous programming in PHP.
stream_set_blocking(resource $stream , bool $enable ): bool. Sets blocking or non-blocking mode on a stream . This function works for any stream that supports non-blocking mode (currently, regular files and socket streams).
Streams are the way of generalizing file, network, data compression, and other operations which share a common set of functions and uses. In its simplest definition, a stream is a resource object which exhibits streamable behavior.
The blocking/non-blocking mode says if the fread/fwrite functions will return immediately. When in non-blocking mode
, they will return any available data. If no data can be read at the time the function is invoked, then none will be returned. Such streams are typicalled polled in a loop.
In blocking mode
however, the function will always wait (and therefore block your programs execution) until it can satisfy the complete read request. If you ask to read 1MB from a network socket, the function will not return until it has received 1MB to pass on.
I think Wikipedia covers it quite well:
http://en.wikipedia.org/wiki/Berkeley_sockets#Blocking_vs._non-blocking_mode
It mostly has effect on networked file/stream sources. For local filesystems the operating system will always read the desired length of data. PHP also has stream wrappers, which can handle that option at their discretion (there's no reliable general rule).
For more low-level details, visit the manpages of fnctl(2) or socket(2) or
http://www.scottklement.com/rpg/socktut/nonblocking.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With