nonblocking STDIN in CLI PHP app

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • yawnmoth

    nonblocking STDIN in CLI PHP app

    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_bloc king($stdin, 0);

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

    Any ideas?

  • yawnmoth

    #2
    Re: nonblocking STDIN in CLI PHP app

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

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

    stream_set_bloc king($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?

    Comment

    • yawnmoth

      #3
      Re: nonblocking STDIN in CLI PHP app

      On May 30, 9:07 pm, yawnmoth <terra1...@yaho o.comwrote:
      I think this is a better way to approach my question. Here's my
      script:
      >
      <?php
      $stdin = fopen('php://stdin', 'r');
      >
      stream_set_bloc king($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:



      Comment

      Working...