Re: Exec Script in the background, don't wait till it finishes

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On Jan 14, 2011, at 12:41 PM, Kai Renz wrote:

> Hi guys and thanks for your answers...
> 
> @Nicholas:
> Yes, you are right. The first socket is only used if a new clients
> connects, thats why the script generates a new port so the client can
> connect to the new socket. After that socket1 should continue its work
> and wait for new clients.
> 
> @Daniel:
> Yeh i tried sending it to the background, this works but still it does
> wait for the other script to finish.
> 
> @Evil Son:
> Thanks for the tip, i'll try it :)
> 
> -- 
> PHP General Mailing List (http://www.php.net/)
> To unsubscribe, visit: http://www.php.net/unsub.php
> 


Your not going to be able to push it to the background, it will always wait no matter where you push it.

You will have to spawn another full script. The pcntl_fork() function is what you are looking for, but it works a tad less than optimal in this situation.


Here is a QnD of a class and using it. This thing creates a bit of a mess, but it illustrates that the parent doesn't wait on the child to die.
You will need to write some logic to determine if it is the parent or child fork that is running, and also keep track of your ports.

Like I said earlier, it creates a mess, but clearly illustrates pcntl_fork(); This is a messy thing to be implementing in PHP.

<?php 
$_pid = getmypid();
echo "\n~~ Start $_pid\t";
$_port = 8080;
$_socket = new MySocket($_port);
$_socket->open();
$_socket->handleNewClient(++$_port);
$_socket->handleNewClient(++$_port);
$_socket->handleNewClient(++$_port);
$_socket->handleNewClient(++$_port);
$_socket->handleNewClient(++$_port);

echo "\n~~ End $_pid\t";

class MySocket {

    private $port;
    
    public function __construct($_port) {
        $this->port = getmypid(); //Use port number if ya want - I used PID for uniqueness
        echo "\n--- Created new port $this->port\t";
    }
    
    public function open() {
        echo "\nOpen port: $this->port\n";
        for ($_i = 0; $_i < 100; $_i++) {// Do some thinking: Clog up the buffer
            echo "[$this->port]";
        }
        
    }
    
    public function close() {
        echo "\n=== Closing $this->port\t";
    }
    
    public function handleNewClient($_port) {
        $_socket = new MySocket($_port);
        $_socket->open();
        pcntl_fork(); // Creates an exponential mess
        $_socket->close(); // Close socket after spawning another script
    }
    
    // Rest of class logic...
}
?>

[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux