0

我有一个守护程序,可以在插入或移除新设备时在终端中打印,现在我希望它像在 linux 中打印的方式一样以 php 打印。这就像实时输出。当新设备插入 linux 时,它会提醒 php,而无需单击它只是在屏幕上打印的任何按钮。我的守护程序在 linux 中打印的内容也是 php 打印的。

我还有另一个扫描设备但不扫描守护进程的程序,我可以毫无问题地获得它的输出并将其打印在 php 中。

我应该如何在 php 中使用我的守护程序进行实时输出?

谢谢,

4

2 回答 2

0

它会在你不点击任何按钮的情况下提醒 php

所以你在谈论客户端PHP。

最大的问题是提醒客户端浏览器。

很短的时间内,您可以忽略该问题并禁用所有缓冲并将守护程序输出发送到浏览器。从长远来看,它既不优雅也不真正起作用,而且它有……审美问题。此外,您根本无法真正操作输出客户端,至少不容易或干净。

所以你需要在客户端运行一个程序,这意味着Javascript。JS 和 PHP 程序必须通信,而且 PHP 还必须与守护进程通信,或者至少监视它在做什么。

有一些方法可以使用 Web Sockets,或者可能是 multipart-x-mixed-replace,但它们还不是很便携。

您可以刷新网页,但这很浪费,而且速度很慢。

在我看来,将通知发送到客户端浏览器的问题最好通过 AJAX 轮询来解决。您不会立即收到警报,但在几秒钟内收到警报。

您将每隔 10 秒(10000 毫秒)从 AJAX 向 PHP 发送一个查询

function poll_devices() {
  $.ajax({
    url: '/json/poll-devices.php',
    dataType: 'json',
    error: function(data) {
      // ...
    },
    success: function(packet) {
       setTimeout(function() { poll_devices(); }, 10000);
       // Display packet information
    },
    contentType: 'application/json'
  });
}

PHP会检查累积日志并发送情况。

另一种可能性是让 PHP 脚本阻塞长达 20 秒,不足以让 AJAX 超时并放弃,并在发生更改时立即返回。然后,您将使用异步 AJAX 函数来驱动轮询背靠背。

这样,异步函数启动并立即进入睡眠状态,同时 PHP 脚本也处于睡眠状态。20 秒后,呼叫返回并立即重新发出,再次休眠。

最终效果是保持一个连接不断打开,并且立即将更改回显到客户端 Javascript。但是,您必须管理连接中断。但是这样一来,每 20 秒您只发出一个呼叫,并且几乎可以立即收到警报。

服务器端 PHP 可以在开始时检查日志文件的大小(保存在会话中的最后读取位置),并在共享模式下保持打开只读fgets(),如果守护程序允许,则使用 阻止读取。

或者您可以将守护进程通过管道传输到logger,并将消息发送到 syslog。配置 syslog 以将这些消息发送到PHP 可读的特定无缓冲文件。现在 PHP 应该能够使用 , 和 完成所有操作fopen()ftell()fgets()无需额外的通知系统。

于 2012-10-04T06:49:41.360 回答
0

Comments becoming long so I add a post here.

First off the redirection of stderr and stdout to file by ~$ my-daemon >> my_logfile 2>&1 - unless your daemon has a log-file option.

Then you could perhaps use inotifywait with the -m flag on modify events (if you want to parse/do something on system outside PHP, i.e. by bash.)

Inotify can give you notification on various changes - This is i..e a short few lines of a bash script I use to check for new files in a specific directory:

notify()
{
    ...

    inotifywait -m -e moved_to --format "%f" "$path_mon" 2>&- |
    awk ' { print $0; fflush() }' |
    while read buf; do
        printf "NEW:[file]: %s\n" "$buf" >> "$file_noti_log"
            blah blah blah
        ...
     done
}

What this does is: each time a file get moved to $path_mon the script enters inside the while loop and perform various actions defined by the script.

Haven't used inotify on PHP but this looks perhaps like what you want: inotify_init (separate module in PHP).

inotify check various events in one or several directories, or you can target a specific file. Check man inotifywait or inotify. You would most likely want to use the "modify" flag, "IN_MODIFY" under PHP: Inotify Constants.

You could also write your own in C. Haven't read this page, but IBM's pages use to be quite OK : Monitor file system activity with inotify

Another option could be to use PCNTL or similar under PHP.

于 2012-10-04T06:16:43.267 回答