Re: process creation

From: Date: Fri, 23 Jan 2009 21:00:25 +0000
Subject: Re: process creation
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-287056@lists.php.net to get a copy of this message
bruce wrote:
A simple question (or so I thought). Does php allow an app to create/start a process/application that can continue to run on its own, after the initiating program/app terminates? It appears that the spawning/forking functions might work, but the child apps would be in a zombie status, and couldn't be killed by an external program.
you keep mentioning this zombie state; make sure that all you're child processes have an exit(); at the end or at the end of the code where they are finished; otherwise you get the xombies! also here is a very simple model you can follow that invariably works for me: this will run 10 worker threads: controller: <?php include './your.framework.php'; for($icount=0;$icount<11;$icount++) {
    include './worker.php';
} ?> worker: <?php $pid=pcntl_fork(); if(!$pid) {
    while(1) {
        if($icount) {
            $offset = $icount * 50;
        } else {
            $offset = 0;
        }
        $db = new mysql_handler( $connection );
        $job_list = new job_list;
        if( $jobs = $job_list->get($offset) ) {
            foreach($jobs as $jdex => $job ) {
                //do something with the job
            }
        } else {
            sleep(10);
        }
    }
} else {
    echo "\ndaemon launcher done id $pid\n";
} ?> the above code is designed to run indefinately in a constant loop which polls a database for work to do this is just a very simple example, there are far more complex ways of doing it, keeping a track of how many processes you have, spawning new ones when you need them etc etc, but this i find works v well for me, the key is the $offset; getting jobs from a database and this literally is the offset used, so if you have say 200 emails to get and each script processes 50 at a time, only 4 of your threads are working, bump it up to 10000 and all of them work until the queue drops; the sleep(10) and the spawn process of about 1 per second ensures that you're polling every second so jobs are picked up quickly. it's a lot of functionality for so little code :)

« previous php.general (#287056) next »