e25pcntl.php

<?php
require_once('env.php');
outBegin();
outH('pcntl fork');
function ti() { return 'getpid=' . posix_getpid() . (new DateTime)->format(' H:i:s.v');}

$vP = 'vP 0';
$vC = 'vC 0';
try { 
    out('begin', ti());
    $msgQ = msg_get_queue(7654, 0666);
    out('msgQ', $msgQ);
    $ls =str_repeat('abcd234rst', 1e8);
    out('memory', memory_get_usage(true), 'strlen', strlen($ls));
    $pid = pcntl_fork();
    out("fork returns $pid",  ti() );
    if ($pid == -1) {
         err('could not fork',  ti() );
    } else if ($pid) {
         // we are the parent
        out("parend $pid, vP=$vP, vC=$vC",  ti() );
        $vP = 'vP 1';
        $w = pcntl_wait($sta, WNOHANG, $ru);
        out("parent vP=$vP, vC=$vC, wait", $w, 'status', $sta, $ru, ti() );
        $vP = 'vP 2';
        # pcntl_wait($status); //Protect against Zombie children
        usleep(3e5);
        out('parent memory', memory_get_usage(true), 'strlen', strlen($ls));
        $ls =str_repeat('ABCD987qrs', 2e8);
        out('parent memory', memory_get_usage(true), 'strlen', strlen($ls));
        $w = pcntl_wait($sta, WNOHANG, $ru);
        out("parent vP=$vP, vC=$vC, 0.3 wait", $w, 'status', $sta, $ru, ti() );
        $mg = null;
        $rc = msg_receive($msgQ, 0, $mT, 9e4, $mg, flags: MSG_IPC_NOWAIT);
        out("msg_receive $rc, ty $mT, message", $mg);
        $vP = 'vP 3';
        $w = pcntl_wait($sta, 0, $ru);
        out("parent  vP=$vP, vC=$vC, waited", $w, 'status', $sta, $ru, ti() );
        out('existstatus', pcntl_wexitstatus($sta));
        $vP = 'vP 4';
   } else {
         // we are the child
        out("child  vP=$vP, vC=$vC, pid $pid",  ti() );
        $vC = 'vC 1';
        out('msg_sned', msg_send($msgQ, 1, ['msgSend' , 1, $vC]));
        out('child memory', memory_get_usage(true), 'strlen', strlen($ls));
        usleep(55e5);
        out('child memory', memory_get_usage(true), 'strlen', strlen($ls));
       out("child  vP=$vP, vC=$vC, 0.5",  ti() );
        $vC = 'vC 2';
        usleep(5e5);
        out("child  vP=$vP, vC=$vC, exiting 0.5 $pid",  ti() );
        $vC = 'vC 3';
        exit(432);
    }
} catch (Throwable $e) {
    out("caught Throwable $e");
}
    out("END $pid",  ti() );
outEnd(__file__);
?>