GNU/Linux >> Belajar Linux >  >> Linux

Jalankan proses dengan output realtime di PHP

Ini berhasil untuk saya:

$cmd = "ping 127.0.0.1";

$descriptorspec = array(
   0 => array("pipe", "r"),   // stdin is a pipe that the child will read from
   1 => array("pipe", "w"),   // stdout is a pipe that the child will write to
   2 => array("pipe", "w")    // stderr is a pipe that the child will write to
);
flush();
$process = proc_open($cmd, $descriptorspec, $pipes, realpath('./'), array());
echo "<pre>";
if (is_resource($process)) {
    while ($s = fgets($pipes[1])) {
        print $s;
        flush();
    }
}
echo "</pre>";

Ini adalah cara yang bagus untuk menampilkan output waktu nyata dari perintah shell Anda:

<?php
header("Content-type: text/plain");

// tell php to automatically flush after every output
// including lines of output produced by shell commands
disable_ob();

$command = 'rsync -avz /your/directory1 /your/directory2';
system($command);

Anda memerlukan fungsi ini untuk mencegah buffering keluaran:

function disable_ob() {
    // Turn off output buffering
    ini_set('output_buffering', 'off');
    // Turn off PHP output compression
    ini_set('zlib.output_compression', false);
    // Implicitly flush the buffer(s)
    ini_set('implicit_flush', true);
    ob_implicit_flush(true);
    // Clear, and turn off output buffering
    while (ob_get_level() > 0) {
        // Get the curent level
        $level = ob_get_level();
        // End the buffering
        ob_end_clean();
        // If the current level has not changed, abort
        if (ob_get_level() == $level) break;
    }
    // Disable apache output buffering/compression
    if (function_exists('apache_setenv')) {
        apache_setenv('no-gzip', '1');
        apache_setenv('dont-vary', '1');
    }
}

Itu tidak berfungsi di setiap server yang telah saya coba, saya harap saya dapat memberikan saran tentang apa yang harus dicari dalam konfigurasi php Anda untuk menentukan apakah Anda harus mencabut rambut Anda untuk mencoba agar perilaku seperti ini berfungsi. di server Anda! Ada yang tahu?

Berikut adalah contoh tiruan dalam PHP biasa:

<?php
header("Content-type: text/plain");

disable_ob();

for($i=0;$i<10;$i++) 
{
    echo $i . "\n";
    usleep(300000);
}

Saya harap ini membantu orang lain yang telah mencari di Google di sini.


Linux
  1. Jalankan Beberapa Contoh Proses Benar Dari Terminal Gnome?

  2. Mengarahkan Output Subkulit ke Proses?

  3. Mewarnai Keluaran Ekor Dengan Sed?

  1. Jalankan Script Dengan Argumen Sebagai Pengguna?

  2. Proses Waktu Mulai Dengan Zona Waktu?

  3. Bagaimana Cara Menjalankan Beberapa versi PHP dengan Nginx di Ubuntu?

  1. Cara memahami keluaran warna

  2. Bagaimana menjalankan proses Rsync di latar belakang

  3. Jalankan skrip php sebagai proses daemon