Date created: Saturday, September 28, 2013 6:03:06 PM. Last modified: Friday, September 15, 2017 10:38:36 AM

Process Control - Child Fork

This script will fork a new process from the parent script, a child, under a new POSIX session. The two processes run side by side and even after the parent is killed, the child continues to run as expected.

pcntl_fork.php

<php

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

$pid = pcntl_fork(); // Fork off a new child

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

if ($pid) { // PID == 0, this is where parent code is executed

    echo "I have a child process, child PID = ".$pid."\n";
    while(true) {
        echo "PARENT - posix_getpid=".posix_getpid().", posix_getppid=".
        posix_getppid()."\n";
        sleep (10);
    }

} else { // Some other number was returned, the PID of new child

    $sid = posix_setsid(); // Place this child process in its own session

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

    echo "\nI am a child process, PID = ".$pid.
    ", posix_getpid=".posix_getpid().", posix_getppid=".
    posix_getppid()."\n";

    while(true) {
        echo "CHILD - posix_getpid=".posix_getpid().", posix_getppid=".
        posix_getppid()."\n";
        sleep (10);
    }

}

>

Previous page: Image Rotor
Next page: Process Control - Fork Chaser