I'm working on an IPC system for the backend of a web IM client coded in PHP. I'm trying to implement Unix sockets, but am having trouble reusing the created socket file. Here is code that listens on a socket for events.
<?php
$socket_file = "../tmp/sockets/test.sock";
$socket = socket_create(AF_UNIX, SOCK_STREAM, 0);
socket_bind($socket, $socket_file);
socket_listen($socket);
socket_select($temp = array($socket), $temp = null, $temp = null, 20);
$client = socket_accept($socket);
socket_set_nonblock($client);
$buffer = socket_read($client, 2048);
echo $buffer;
socket_close($client);
socket_close($socket);
When this script is run the first time, it creates the socket file test.sock and waits for connections. Then when I run the sending script:
<?php
$socket = socket_create(AF_UNIX, SOCK_STREAM, 0);
socket_connect($socket, "../tmp/sockets/test.sock");
$msg = "
This is a test
";
socket_write($socket, $msg, strlen($msg));
socket_close($socket);
The other script will output the received message and exit. So everything up until this point is working the way I expect it to. The problem is when I try to re-execute the listening script it throws this error:
Warning: socket_bind() [function.socket-bind]: unable to bind address [98]: Address already in use
If I run
rm ~/tmp/sockets/test.sock
Then rerun the listen script it recreates the socket file and works fine. So my question is: is there anyway for a listen script reconnect to an existing socket file, and can a sending script write to a socket even when another script isn't connected and listening on that socket file? I'm new to the concept of unix sockets so any help would be greatly appreciated!
socket_close() does not remove the file, you need to do that manually (unlink()) As for your second question, I imagine it may be able to connect, but whatever it sends will be dropped. just try it.
Take a look at unix(7)
manual page. Towards the end it says:
Binding to a socket with a filename creates a socket in the file system that must be deleted by the caller when it is no longer needed (using `unlink(2)`). The usual UNIX close-behind semantics apply; the socket can be unlinked at any time and will be finally removed from the file system when the last reference to it is closed.
So just remove the socket file right after the socket_bind()
in the server.