I need to write some service for my application. I want each client to have limited persistent connections (like only allow first 10 clients to connect).
I know I can listen on the port with PHP by socket_listen(). The parent process accept the connection, then pcntl_fork() the process to have children to handle connection.
But as far as I know, PHP resources doesn’t persist when fork()ed. I wonder if it is possible to do this with PHP, or I have to do this in C?
1)
Why bother forking? Run your daemon as a single process and use socket_select() ( or stream_select) to listen for requests.
See Aleksey Zapparov’s code here for a ready-written solution.
2)
Why bother with the pain of writing your own socket code – use [x]inetd to manage the servers and do al the communication on stdio (note that unlike solution 1, there will be a seperate process for each client – therefore the handling code will be non-blocking)
—
You are correct in saying that PHP resources should not be available in a forked process – but give no indication of how this relates to your current problem. Is it just so that you can count the number of connections? Or something else? In the case of the former, there are much easier ways of doing this. Using solution 1, just increment and decrement a counter variable when clients connect/disconnect. In the case of 2, the same approach but keep the variable in a datafile/database (you might also want to store info about the connections and run occasional audits). Alternatively limit the connections on the firewall.
C.