Tail -f живой процесс вывода все еще работает - PullRequest
0 голосов
/ 11 февраля 2019

Я пытаюсь сделать прямой вывод файла с именем fail2ban.log, этот журнал находится на моем сервере Linux, и я пытаюсь обработать его, используя.Конечный процесс остается открытым, поэтому он использует нагрузку на производительность процессора после того, как некоторые люди открывают страницу, так как процесс остается открытым

Я попытался решить проблему с помощью

while(true)
{
if($flag === false) die(); // Or exit if you prefer
}

Сервер включенApache2

Мой код:

<code><?php
echo "Number of banned ip (live) : ";
$hand = popen("grep 'Ban' /var/log/fail2ban.log | wc -l 2>&1", 'r');
while(!feof($hand)) {
    $buff = fgets($hand);
    echo "$buff<br/>\n";
    ob_flush();
    flush();
}
pclose($hand);
echo " ";
echo "Current Log (go at the bottom of the page for the live log)";
echo " ";
$output = shell_exec('cat /var/log/fail2ban.log 2>&1');
echo "<pre>$output
"; echo" Live Logs "; echo"

"; echo" "; $ handle = popen (" tail -f / var /log / fail2ban.log 2> & 1 ", 'r'); while (! feof ($ handle)) {$ buffer = fgets ($ handle); echo" $ buffer\ n "; ob_flush (); flush ();} pclose ($ handle);?>>

Я хочу завершить процесс, когда пользователь закроет страницу.

1 Ответ

0 голосов
/ 11 февраля 2019

Нет @jhnc В этом случае popen виновен, что не завершает процесс при закрытии программы.

В общем, PHP - один из худших вариантов реализации tail -f.Лучше использовать узел + веб-сокет.

В этом случае вам нужно проверить, было ли что-то добавлено в файл другим методом.С http://php.net/manual/en/function.inotify-init.php#101093

<?php
/**
* Tail a file (UNIX only!)
* Watch a file for changes using inotify and return the changed data
*
* @param string $file - filename of the file to be watched
* @param integer $pos - actual position in the file
* @return string
*/
function tail($file,&$pos) {
    // get the size of the file
    if(!$pos) $pos = filesize($file);
    // Open an inotify instance
    $fd = inotify_init();
    // Watch $file for changes.
    $watch_descriptor = inotify_add_watch($fd, $file, IN_ALL_EVENTS);
    // Loop forever (breaks are below)
    while (true) {
        // Read events (inotify_read is blocking!)
        $events = inotify_read($fd);
        // Loop though the events which occured
        foreach ($events as $event=>$evdetails) {
            // React on the event type
            switch (true) {
                // File was modified
                case ($evdetails['mask'] & IN_MODIFY):
                    // Stop watching $file for changes
                    inotify_rm_watch($fd, $watch_descriptor);
                    // Close the inotify instance
                    fclose($fd);
                    // open the file
                    $fp = fopen($file,'r');
                    if (!$fp) return false;
                    // seek to the last EOF position
                    fseek($fp,$pos);
                    // read until EOF
                    while (!feof($fp)) {
                        $buf .= fread($fp,8192);
                    }
                    // save the new EOF to $pos
                    $pos = ftell($fp); // (remember: $pos is called by reference)
                    // close the file pointer
                    fclose($fp);
                    // return the new data and leave the function
                    return $buf;
                    // be a nice guy and program good code ;-)
                    break;

                    // File was moved or deleted
                case ($evdetails['mask'] & IN_MOVE):
                case ($evdetails['mask'] & IN_MOVE_SELF):
                case ($evdetails['mask'] & IN_DELETE):
                case ($evdetails['mask'] & IN_DELETE_SELF):
                    // Stop watching $file for changes
                    inotify_rm_watch($fd, $watch_descriptor);
                    // Close the inotify instance
                    fclose($fd);
                    // Return a failure
                    return false;
                    break;
            }
        }
    }
}

// Use it like that:
$lastpos = 0;
$file = '/var/log/fail2ban.log'l
while (true) {
    echo tail($file,$lastpos);
    ob_flush();
    flush();
}
?>

И вы не можете забыть о max_execution_time и ограничениях Apache

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...