Process Control - Fork Chaser

This script uses process control to fork a child process in a new session detached from the parent, the parent dies and the child continues code execution. This create a looping scenario whereby a child is started, the parent dies, and so the process ID is ever changing. If the parent code section were changed, the exit statement removed and the same exec statement from the child section added, it would be a fork bomb with parents and children executing more instances of the same script. Instead, this script simply creates new children instances of its self, killing the parent each time. To successfully kill it you need to chase down the PID of the current child instance, hense the sleep statement.



// CLI arguments to PHP binary, to run a new copy of this script
$ARGS=Array("-f", __FILE__);

echo "PARENT - posix_getpid=".posix_getpid().", posix_getppid=".posix_getppid()."\n";

$pid = pcntl_fork();

if ($pid == -1) die("Could not fork a new child\n");

if ($pid) {

    // This is a parent, so quit

} else {

    // This is a child, fork new children
    $sid = posix_setsid();

    if ($sid < 0)
        die("Child posix_setsid error\n");

    echo "I am a child process, PID = ".$pid.
    ", posix_getpid=".posix_getpid().", posix_getppid=".

    pcntl_exec(PHP_BINARY, $ARGS);



Previous page: Process Control - Child Fork
Next page: PingyThingy