Skip to content

Instantly share code, notes, and snippets.

@tored
Last active September 20, 2016 08:55
Show Gist options
  • Select an option

  • Save tored/ac828d910c9ab287d425715b3dcad9e1 to your computer and use it in GitHub Desktop.

Select an option

Save tored/ac828d910c9ab287d425715b3dcad9e1 to your computer and use it in GitHub Desktop.

Revisions

  1. tored revised this gist Sep 20, 2016. 1 changed file with 2 additions and 0 deletions.
    2 changes: 2 additions & 0 deletions fork.php
    Original file line number Diff line number Diff line change
    @@ -1,3 +1,5 @@
    <?php

    function fork($program, ...$args): int
    {
    if (strtoupper(php_uname('s')) === 'WINDOWS NT') {
  2. tored revised this gist Sep 20, 2016. No changes.
  3. tored created this gist Sep 20, 2016.
    54 changes: 54 additions & 0 deletions fork.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,54 @@
    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];
    }