Skip to content

Instantly share code, notes, and snippets.

@andyg2
Last active December 14, 2022 20:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andyg2/23dc0e0e7e91ff2e434351158058a612 to your computer and use it in GitHub Desktop.
Save andyg2/23dc0e0e7e91ff2e434351158058a612 to your computer and use it in GitHub Desktop.
Script to spawn a bunch of CLI scripts in the background and restart any that fail.
<?php
$scripts = [];
$scripts[] = 'ping google.com > google.txt';
$scripts[] = 'ping msn.com > msn.txt';
function spawn_scripts($scripts) {
$pids = [];
// iterate scripts, building list of indexed PIDs
foreach ($scripts as $ix => $script) {
$pids[$ix] = shell_exec("nohup $script > /dev/null 2>&1 & echo $!");
}
while (true) {
// iterate indexed PIDs, respawning any scrip[t that's not running
foreach ($pids as $ix => $pid) {
$res = shell_exec("ps -p $pid");
if (count(preg_split("/\n/", $res)) <= 2) {
shell_exec("nohup $scripts[$ix] > /dev/null 2>&1 & echo $!");
}
}
sleep(5);
// check for kill file
if( file_exists( 'killnohup' ) ) {
$killcommand = 'ps -ef | grep nohup | awk '{print $2}' | xargs kill -9';
shell_exec( $killcommand );
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment