Created
March 2, 2015 12:19
-
-
Save meglio/565f9a3644eb656586cd to your computer and use it in GitHub Desktop.
Run any command in background from PHP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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