Gunakan fungsi ini untuk menjalankan program Anda di latar belakang. Ini lintas platform dan sepenuhnya dapat disesuaikan.
<?php
function startBackgroundProcess(
$command,
$stdin = null,
$redirectStdout = null,
$redirectStderr = null,
$cwd = null,
$env = null,
$other_options = null
) {
$descriptorspec = array(
1 => is_string($redirectStdout) ? array('file', $redirectStdout, 'w') : array('pipe', 'w'),
2 => is_string($redirectStderr) ? array('file', $redirectStderr, 'w') : array('pipe', 'w'),
);
if (is_string($stdin)) {
$descriptorspec[0] = array('pipe', 'r');
}
$proc = proc_open($command, $descriptorspec, $pipes, $cwd, $env, $other_options);
if (!is_resource($proc)) {
throw new \Exception("Failed to start background process by command: $command");
}
if (is_string($stdin)) {
fwrite($pipes[0], $stdin);
fclose($pipes[0]);
}
if (!is_string($redirectStdout)) {
fclose($pipes[1]);
}
if (!is_string($redirectStderr)) {
fclose($pipes[2]);
}
return $proc;
}
Perhatikan bahwa setelah perintah dimulai, secara default fungsi ini menutup stdin dan stdout dari proses yang berjalan. Anda dapat mengarahkan proses output ke beberapa file melalui argumen $ redirectStdout dan $ redirectStderr.
Catatan untuk pengguna windows:
Anda tidak dapat mengalihkan stdout / stderr ke nuldengan cara berikut:
startBackgroundProcess('ping yandex.com', null, 'nul', 'nul');
Namun, Anda dapat melakukan ini:
startBackgroundProcess('ping yandex.com >nul 2>&1');
Catatan untuk * nix pengguna:
1) Gunakan perintah exec shell jika Anda ingin mendapatkan PID aktual:
$proc = startBackgroundProcess('exec ping yandex.com -c 15', null, '/dev/null', '/dev/null');
print_r(proc_get_status($proc));
2) Gunakan argumen $ stdin jika Anda ingin meneruskan beberapa data ke input program Anda:
startBackgroundProcess('cat > input.txt', "Hello world!\n");