By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
434,870 Members | 2,484 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 434,870 IT Pros & Developers. It's quick & easy.

nonblocking STDIN in CLI PHP app

P: n/a
For learning purposes, I'd like to create a PHP script that'll output
the system time every minute and, at the same time, will process
"command line" commands as I type them into STDIN. eg.

If I wait a minute, it should output the time. If, ten seconds later,
I type in "dir", it should display the directory information.
Unfortunately, it doesn't do that.

Here's my code:

<?php
$stdin = fopen('php://stdin', 'r');

stream_set_blocking($stdin, 0);

$data = '';
$last_date = '';
while (true)
{
$data.= fgets($stdin, 1024);
if ($data{strlen($data)-1} == "\r" || $data{strlen($data)-1} == "\n")
{
system(trim($data));
$data = '';
}
if ($last_date != date('g:ia'))
{
$last_date = date('g:ia');
echo "\r\nThe time is now [$last_date]\r\n";
}
}
?>

Any ideas?

May 31 '07 #1
Share this Question
Share on Google+
2 Replies


P: n/a
I think this is a better way to approach my question. Here's my
script:

<?php
$stdin = fopen('php://stdin', 'r');

stream_set_blocking($stdin, false);

$last_date = '';
while (true)
{
fread($stdin, 1024);
if ($last_date != date('g:ia'))
{
$last_date = date('g:ia');
echo "The time is now [$last_date]\r\n";
}
}

If I comment out the fread, it echo's the time once a minute. If I
leave the fread as it is, it doesn't. My question is... why?
Blocking is set to false, so why does it appear to be blocking, anyway?

May 31 '07 #2

P: n/a
On May 30, 9:07 pm, yawnmoth <terra1...@yahoo.comwrote:
I think this is a better way to approach my question. Here's my
script:

<?php
$stdin = fopen('php://stdin', 'r');

stream_set_blocking($stdin, false);

$last_date = '';
while (true)
{
fread($stdin, 1024);
if ($last_date != date('g:ia'))
{
$last_date = date('g:ia');
echo "The time is now [$last_date]\r\n";
}

}

If I comment out the fread, it echo's the time once a minute. If I
leave the fread as it is, it doesn't. My question is... why?
Blocking is set to false, so why does it appear to be blocking, anyway?
Never mind... I think the following URL addresses my problem:

http://bugs.php.net/34972

May 31 '07 #3

This discussion thread is closed

Replies have been disabled for this discussion.