3

我在互联网上找不到太多关于 PHP CLI 的信息,所以我很难弄清楚如何完成我的代码。

基本上,应用程序应该继续每 2 秒检查一次 MYSQL 数据库而不退出,除非用户输入了字母“q”。

在我实现 MYSQL 之前,我只是通过连续打印“pro”这个词来开始它,所以我的代码看起来像这样:

<?php
    fwrite(STDOUT, "This should print word 'pro' continuously\n");
    fwrite(STDOUT, "\tto exit, simply press 'q' and enter\n");

    do {
        fwrite(STDOUT, "pro\n");
    }while (fgetc(STDIN) != 'q');
?>

几乎当用户输入'q'时,应用程序终止,但问题是它只打印出'pro'一次,当我按下回车时。

4

2 回答 2

2

fgetc()将阻塞直到有数据要读取 - 换句话说,当脚本到达fgetc()调用时,执行将停止,直到用户输入某些内容。

为了解决这个问题,您需要检查是否有任何数据可以使用stream_select(). 您还可以使用stream_select()将 MySQL 轮询限制为每 2 秒一次。一个基本的框架看起来像这样:

<?php

  // Do all your init work here, connect to DB etc
  $tickerSecs = 2;
  echo "Hello! I've started\n";

  do {

    // Do actual work here
    echo "I'm polling the database\n";

    // See stream_select() docs for an explanation of why this is necessary
    $r = array(STDIN);
    $w = $e = NULL;
    if (stream_select($r, $w, $e, $tickerSecs) > 0) {
      // The user input something
      echo "You input something\n";
      $char = fread(STDIN, 1);
      if ($char == 'q') {
        // The user pressed 'q'
        echo "You told me to quit\n";
        break;
      } else {
        echo "I don't understand '$char'\n";
      }
    }

  } while (TRUE); // Loop forever

  // Do shutdown work here
  echo "I'm shutting down\n";

请注意,您可能不得不要求您的用户按下q + enter,而不仅仅是q因为这些事情的工作方式的性质 - 我真的不明白为什么会这样,也许其他人可以在这里提供缺失的部分?

于 2012-08-02T11:09:40.647 回答
0

您可以使用 pcntl_signal() 为 SIGQUIT 注册处理程序(即 Ctrl-C),而不是在按下 Q 时停止

于 2012-08-02T11:59:49.047 回答