note 101968 deleted from function.pcntl-fork by danbrown
| From: | danbrown@php.net | Date: | Thu, 20 Jan 2011 18:22:01 +0000 |
| Subject: | note 101968 deleted from function.pcntl-fork by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-175944@lists.php.net to get a copy of this message | ||
Note Submitter: MasterM
----
I tried to make a MultiPlayer game server using PHP.
Main idea is to create 1 child process per 1 client using socket connection.
When a client connected to server, 1 of child process will be created. That means if we have many
client connected to the server at the same time, All of variables in each process (parent, child) is
saparated independently and i don't know how to share some variables among processes.
I tried sharemem and semaphore. But they couldn't store socket resources.
This is the big problem. Please see code.
(Thread is a class that applied pcntl_fork, fork a new child process for running particular function
like C language. I got from http://downloads.motane.lu/Thread.php)
$clients = $threads = array();
$index = 0;
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create
socket\n");
$result = socket_bind($socket, $host, $port) or die("Could not bind tosocket\n");
$result = socket_listen($socket, 3) or die("Could not set up socket listener\n");
// keep looping and looking for client input
do
{
$client = $clients[] = socket_accept($socket) or die("Could not accept incoming
connection\n");
if($client)
{
$threads[$index] = new Thread( 'ClientHandler' ); // <<---
create child process
$threads[$index]->start( $client ); // child process jump to run
ClientHandler immediately.
echo "Create Thread
#".$threads[$index]->getPid()."\n";
$index++;
}
} while (true);
function ClientHandler()
{
//child process function only
... ??????how to refer to $GLOBALS['clients'][index] in parent process, not in child
process, Because $clients in child is not up to date....
}
Idea,
Parent process
- wait and accept new client
- keep up to date socket resources (add, remove socket)
- fork new child
Child process
- run handler function only.
Above code you will see that after socket_accept.
Parent process just wait for incomming connection from client,put the socket resource to array
$clients and fork a new client and running handler function ClientHandler.
Variable $clients(in parent process) will keep socket resources of all connection and may be
increase and decrease depends on amount of client that connect to the server. After a new child
process is created for running function ClientHandler.
How child process refers to "$clients" resource variable in parent process...
I tried to access $GLOBAL['clients'][] but it reference to $clients in child process (old
resource that copied from parent when it's created.)