Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Blocking and non-blocking modes in PHP Streams

Tags:

php

stream

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.

like image 645
amateur barista Avatar asked Mar 14 '11 03:03

amateur barista


People also ask

Is PHP blocking or nonblocking?

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.

What is Stream_set_blocking?

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).

What are streams in PHP?

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.


1 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

like image 56
mario Avatar answered Oct 05 '22 23:10

mario