Utilizzare questa funzione per eseguire il programma in background. È multipiattaforma e completamente personalizzabile.
<?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;
}
Si noti che dopo l'avvio del comando, per impostazione predefinita questa funzione chiude lo stdin e lo stdout del processo in esecuzione. È possibile reindirizzare l'output del processo in alcuni file tramite gli argomenti $ redirectStdout e $ redirectStderr.
Nota per gli utenti di Windows:
non è possibile reindirizzare stdout / stderr nulnel modo seguente:
startBackgroundProcess('ping yandex.com', null, 'nul', 'nul');
Tuttavia, puoi farlo:
startBackgroundProcess('ping yandex.com >nul 2>&1');
Note per gli utenti * nix:
1) Utilizzare il comando exec shell se si desidera ottenere il PID effettivo:
$proc = startBackgroundProcess('exec ping yandex.com -c 15', null, '/dev/null', '/dev/null');
print_r(proc_get_status($proc));
2) Utilizzare l'argomento $ stdin se si desidera passare alcuni dati all'input del programma:
startBackgroundProcess('cat > input.txt', "Hello world!\n");