process from pcntl_fork not terminating

2019-06-07 14:51发布

问题:

I am running a web service which involved with daemons by php+apache2. So I tried pcntl_fork function. But there is a question that the child process are not terminating even I used exit(0) in the child process's code which result in a lot of apache2 processes.

I'm wondering if there is a way to shutdown those useless apache2 processes?

PS: because I'm not very aware of the mechanism of signal, so I tried to make daemon by a single call to a agent script which will exit as soon as the child is created.

switch ($_GET['action']){
    case "new":
        $pid = pcntl_fork();
        switch ($pid){
            case -1: 
                echo "failed to create daemon";
                exit;
            case 0:
                //Code here
                exit(0);
                break;
            default:
                echo "Daemon PID:$pid";
        }
}

And I'm planning to use a file to control the daemon. For example I will append a line like "exit" to the daemon's control file such as "1.txt" to let it shutdown itself.

PPS: After reading this topic: pcntl_fork() results in defunct parent process, I'm curious about that if the zombie process bug caused the bug.

回答1:

You should have to use this function:

http://php.net/manual/en/function.pcntl-wait.php

But generally under Apache forking is probably not a good idea.