1

I'm very new to PHP so this might be something simple. Anyway, I'm trying to create 2-way communication between a PHP script (activated by a web client) and a local process (written in C++). The PHP script should send some information to the C++ process and then wait for a response. My problem is that the only way to set up this kind of communication seems to be to use socket_bind, but when I do, it fails with the 'address already in use' error. The socket file in question, /tmp/sock, has already been created by the C++ process, which is running continuously (it can not be launched by the PHP script). If I use socket_connect and just write something to the C++ process, that works just fine; but I need to bind before I can listen to that socket from the PHP script. Here's my code:

<?php
error_reporting(E_ALL);

/* Allow the script to hang around waiting for connections. */
set_time_limit(0);

/* Turn on implicit output flushing so we see what we're getting
 * as it comes in. */
ob_implicit_flush();

//Adapted from http://www.php.net/manual/en/sockets.examples.php

if (($sock = socket_create(AF_UNIX, SOCK_STREAM,0)) === false) 
{
    echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
    exit();
}
if (socket_bind($sock, '/tmp/sock') === false)  //Fails here
{
    echo "socket_bind() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
}  
....

Thanks--

Matt Phillips
  • 9,465
  • 8
  • 44
  • 75

2 Answers2

2

Your C++ and PHP codes have to mark the socket as shared (SO_REUSE_ADDR).

user703016
  • 37,307
  • 8
  • 87
  • 112
  • Thanks--I added socket_set_option($sock, SOL_SOCKET, SO_REUSEADDR, 1) to my script, and while it didn't return an invalid operation error, I still had the same problem. Is there something else I need to do with the C++ (Qt)? I've use QLocalSockets before without anything explicit about sharing, and not had a problem. /tmp/sock is 777, permissions-wise. – Matt Phillips Apr 22 '11 at 13:49
  • @Haendel I'm not sure what you have in mind, this problem arises before I would ever want to close a socket. – Matt Phillips Apr 22 '11 at 19:34
0

It turns out that what's needed is simply socket_read(). I didn't realize you could do both operations on the same socket (when it was merely connected and not bound). User hamishcool3 at PHP socket_read has a great utility function for reading from a socket until a particular character is reached (though it is probably slower than a standard byte-limited read).

Matt Phillips
  • 9,465
  • 8
  • 44
  • 75