Skip to content

Instantly share code, notes, and snippets.

@tored
Last active September 20, 2016 08:55
Show Gist options
  • Save tored/ac828d910c9ab287d425715b3dcad9e1 to your computer and use it in GitHub Desktop.
Save tored/ac828d910c9ab287d425715b3dcad9e1 to your computer and use it in GitHub Desktop.
fork - simple fork for both Windows (with PowerShell) and Un*x (with Bash) in PHP. Returns PID.
<?php
function fork($program, ...$args): int
{
if (strtoupper(php_uname('s')) === 'WINDOWS NT') {
$cmd = [
'powershell.exe',
'-Command',
'$proc',
'=',
'Start-Process',
escapeshellarg($program),
];
if (count($args)) {
$cmd[] = '-ArgumentList';
}
foreach ($args as $key => $arg) {
$cmd[] = escapeshellarg($arg);
if ($key < count($args) - 1) {
$cmd[] = ',';
}
}
$cmd = array_merge($cmd, [
'-PassThru',
';',
'echo',
'$proc.id',
]);
} else {
$cmd = [
escapeshellcmd($program)
];
foreach ($args as $arg) {
$cmd[] = escapeshellarg($arg);
}
$cmd = array_merge($cmd, [
'>',
'/dev/null',
'2>',
'/dev/null',
'&',
'echo',
'$!',
]);
}
$command = implode(' ' , $cmd);
exec($command, $output, $return);
if ($return !== 0) {
throw new RuntimeException("Failed starting $command");
}
if (!count($output)) {
throw new RuntimeException("Fatal error for $command");
}
return (int) $output[0];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment