php pcntl forking

raw

forktest.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<?php
$pid = pcntl_fork();
if ($pid == -1) {
    die('could not fork');
} else if ($pid) {
    echo "forked\n";
    // we are the parent
    $start = time();
    $exited = false;
    do {
        sleep(1);
        echo "check child status pid $pid\n";
        $ret = pcntl_waitpid($pid, $status, WNOHANG | WUNTRACED);
        echo "status:\n";
        if ($ret > 0) {
            $exitcode = pcntl_wexitstatus($status);
            echo " just exited with status $exitcode\n";
            $exited = true;
            break;
        } else if ($ret == 0) {
            echo " not exited\n";
        } else {
            //error
            echo " error\n";
            break;
        }
    } while (time() < $start + 3);
    echo "child wait done\n";
    if (!$exited) {
        echo "killing\n";
        posix_kill($pid, 9);
    }
} else {
    // we are the child
    echo "hi this is the child\n";
    sleep(5);
    echo "foo\n";
    exit(2);
}
 
?>
 
Christian Weiske Christian Weiske
owner

History