0

I am new on PHP forking and I just copy this code sample from PHP.net. Basically I have a tool that monitor a device and save the data into a database. This tool is running in background.

here is my code:

for(;;)
{
//build connection
$conn = mysql_connect(DB_HOST, DB_USERNAME, DB_PASSWORD);
//select db
mysql_select_db(DB_NAME);

$sql='SELECT * FROM tbl';
$query=mysql_query($sql,$conn);
$zpid=array();
while($res=mysql_fetch_assoc($query))
{

    $pid = pcntl_fork();
    $execute=0;
    if ($pid == -1) 
    {
       echo("could not fork");
    } 
    elseif ($pid) 
    {

        $execute++;
        //pcntl_wait($status);
        if ($execute>=5)
        {
            $child=pcntl_wait($status);
            if($child)
            {
                $execute--;
                echo 'exited child'.$child;
            }

        }
    } 
    else 
    {
        $obj=new Monitor($res['ip'],$res['community_string'],$res['id']);
        $obj->execute();

        //save
        $obj->insert_data();
       sleep(10);   
       exit();
    }
}

mysql_close($conn);
sleep(60);
}

But when the tool run it will produce a zombie process. What will I do to prevent this zombie or defunct process on our server. Please help me. thanks in advance

  • what is **zombie process** ? – NullPoiиteя May 16 '13 at 05:34
  • [**Please, don't use `mysql_*` functions in new code**](http://bit.ly/phpmsql). They are no longer maintained [and are officially deprecated](https://wiki.php.net/rfc/mysql_deprecation). See the [**red box**](http://j.mp/Te9zIL)? Learn about [*prepared statements*](http://j.mp/T9hLWi) instead, and use [PDO](http://php.net/pdo) or [MySQLi](http://php.net/mysqli) - [this article](http://j.mp/QEx8IB) will help you decide which. If you choose PDO, [here is a good tutorial](http://www.brightmeup.info/article.php?a_id=2). – NullPoiиteя May 16 '13 at 05:34

1 Answers1

0

A zombie process is one which has terminated but not yet had its exit status read. This happens when its parent has not (yet) called wait() to read that exit status. pcntl_wait() here is that call, but it must be called for each child, most likely in a while($execute) after the forks. This code never calls it for the first 4 children.

Yann Vernier
  • 15,414
  • 2
  • 28
  • 26
  • thanks for your response..on my implementation I want max five multiple process running at same time. how will i track the first 4 children process be called wait() to read that exit status? – Rey Papellero May 16 '13 at 05:51