Social security for getting on a large amount Beat The Cycle Of Debt Beat The Cycle Of Debt for an approved in addition questions.

Restarting Apache kills script

Posted: June 12th, 2012 | Author: | Filed under: Linux, Tech | Tags: , , , , , , , , , , , , , , , , , , | No Comments »

Another pretty specific problem.  If you have a bash script or any script that you gave sufficient privileges in the sudoers file and want the apache process to run.  If apache starts the processes directly with nohup or disown, etc. when you restart apache all of those child processes die. The workaround/logic is this:

1. Call initial php file through the browser

2. That file uses PHP Exec to call another php file through the command line

3. The command line PHP file forks twice and then calls whatever command/script that will be independent of the apache process.

 

Thanks to Jacob Kiers for having the ONLY site to describe this issue on the internet.
His site is here.

Our example

First file: 

<?php
$name = $_POST['name'];
exec(‘php ‘ . EQ_APP_PATH . ‘/scripts/thread_start.php ‘ . $name);
?>
Second file:

<?php

$name = $argv[1];
/* Fork once */

$pid = pcntl_fork();

if ($pid === -1) {
die(‘First fork failed!’);
} else if ($pid) { // if parent
exit(0);
}

/* Fork again (as session leader) */

posix_setsid(); // become session leader

$pid = pcntl_fork();

if ($pid === -1) {
die(‘Second fork failed!’);
} else if ($pid) { // if parent
exit(0);
}
exec(‘nohup sudo ‘ . dirname(__FILE__) . ‘/thread_start.sh ‘ . $name . ‘ > /dev/null 2>&1 &’);

?>
At the end of the above file, you call your script with nohup that will be independent of the apache process.
This way if you start the process with a webpage/apache, it will not die when apache is restarted or crashes.