Blocking and non-blocking modes in PHP Streams

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.

Answers


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


Need Your Help

Pass extra parameter to jQuery getJSON() success callback function

javascript jquery json

I've never had to use callback functions before, so I may have made a completely stupid mistake. I think I somewhat understand the problem here, but not how to solve it.