I’m using the PHP sockets extension (basically a wrapper around the socket(2)-related linux syscalls) and would like to re-use sockets I open while serving one request in the subsequent ones. Performance is a critical factor.
The sockets I open are all to the same IP, which makes the use of other functions like pfsockopen() impossible (because it reuses same single socket every time) and I need several at a time.
The question
If I leave the sockets I open serving one request deliberately open, (I don’t call socket_close() or socket_shutdown()) and connect a socket with the exact same parameters to the same IP serving the next request; will linux re-use the previously opened socket / file-descriptor?
What I want to do in the end is to avoid TCP-handshakes on every request.
Additional information:
-
I use the apache worker MPM – which means that different request can be but are not necessarily served from different processes. For the sake of simplicity let’s assume that all requests are served from the same process.
-
I can get the file-descriptor ID of a open and connected socket in PHP. I can open and read and write to
/dev/fd/{$id}, yet to no purpose – it’s not communicating with the remote server (maybe this is a naïve approach). If anybody knew how to make this work I’d consider that to be an acceptable answer too.
While the answer given by Jirka Hanika is correct for most systems, I have come to the conclusion that it regretfully does not apply to PHP; the re-use of sockets using the PHP sockets extension is impossible to achieve from user space.
The code that led to this conclusion is:
This code will
stat()the current process’ open socket file descriptors at the start and end of its’ execution. In between it will open a socket withSO_KEEPALIVEset, write a request to it and read a response. Then it will optionally close the socket (toggle line comment) and echo the current process’ PID (to make sure you’re in the same process).You will see that regardless if you close the socket or not, the file descriptor created serving the previous request will not exist anymore at the beginning of this cycle’s execution and a completely new socket will be created and connected.
I was unable to test
SOCK_CLOEXECsince it’s not (yet?) implemented in the extension.(This was tested using PHP 5.4.0)