A way to have a non-blocking pipe reader is to check first if the pipe exists. If so, then read from the pipe, otherwise do other stuff. This will work assuming that the writer creates the pipe, writes on it, and after that deletes the pipe.
This is a blocking writer:
<?php
$pipe="/tmp/pipe";
$mode=0600;
if(!file_exists($pipe)) {
// create the pipe
umask(0);
posix_mkfifo($pipe,$mode);
}
$f = fopen($pipe,"w");
fwrite($f,"hello"); //block until there is a reader
unlink($pipe); //delete pipe
?>
And this is the non-blocking reader:
<?php
$pipe="/tmp/pipe";
if(!file_exists($pipe)) {
echo "I am not blocked!";
}
else {
//block and read from the pipe
$f = fopen($pipe,"r");
echo fread($f,10);
}
?>
posix_mkfifo
(PHP 4, PHP 5)
posix_mkfifo — fifo スペシャルファイル(名前付きパイプ)を作成する
説明
bool posix_mkfifo ( string $pathname, int $mode )posix_mkfifo() は、 FIFO スペシャルファイルを作成します。 これはファイルシステム内に存在し、プロセス間の双方向通信の末端として 動作します。
パラメータ
- pathname
FIFO ファイルへのパス。
- mode
2 番目のパラメータ mode は、8 進表記 (例: 0644)で指定する必要があります。新しく作成される FIFO のパーミッションは、現在の umask() の設定にも依存します。 作成されるファイルのパーミッションは (mode & ~umask) となります。
返り値
成功した場合に TRUE を、失敗した場合に FALSE を返します。
注意
注意: セーフモード が有効の場合、PHP は操作を行うファイル/ディレクトリが実行するスクリプトと 同じ UID (所有者)を有しているかどうかを確認します。
posix_mkfifo
Enric Jaen
17-Aug-2007 01:22
17-Aug-2007 01:22
Uther Pendragon
19-May-2007 06:12
19-May-2007 06:12
Note (quoted from `man 7 pipe` on debian linux):
"On some systems (but not Linux), pipes are bidirectional: data can be transmitted in both directions between the pipe ends. According to POSIX.1-2001, pipes only need to be unidirectional. Portable applications should avoid reliance on bidirectional pipe semantics."
Linux pipes are NOT bidirectional.
Also, it appears to me that the use of fifo (named) pipes in php is pretty pointless as there appears to be NO way of determining whether opening (let alone reading) from it will block. stream_select SHOULD be able to accomplish this, unfortunatly you cannot get to this point because even trying to OPEN a pipe for read will block until there is a writer.
I even tried to use popen("cat $name_of_pipe", 'r'), and even it blocked until it was opened for write by another process.