Skip to content

Instantly share code, notes, and snippets.

@meglio
Created March 2, 2015 12:19
Show Gist options
  • Save meglio/565f9a3644eb656586cd to your computer and use it in GitHub Desktop.
Save meglio/565f9a3644eb656586cd to your computer and use it in GitHub Desktop.
Run any command in background from PHP
<?php
namespace _\sys;
use RuntimeException;
class BackgroundProcess
{
/**
* Theory:
* - http://stackoverflow.com/a/7149229/335304
* - http://ua1.php.net/shell_exec#59898
* - http://nsaunders.wordpress.com/2007/01/12/running-a-background-process-in-php/
* @param $cmd
* @param int $nicenessAddition
* @return array
* @throws \RuntimeException
*/
static function run($cmd, $nicenessAddition = 0)
{
$s = '';
if ($nicenessAddition)
$s .= 'nice -n ' . $nicenessAddition . ' ';
$s .= $cmd . ' &';
$p = proc_open($s, array(), $pipes);
if (!is_resource($p))
throw new RuntimeException('Cannot start command ' . $cmd . ' in background with using: ' . $s);
proc_close($p);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment