It took some time to understand how one PHP process can communicate with another by means of unix udp sockets. Examples of 'server' and 'client' code are given below. Server is assumed to run before client starts.



'Server' code

<?php

if (! extension_loaded ( 'sockets' )) {

die( 'The sockets extension is not loaded.' );

}

$socket = socket_create ( AF_UNIX , SOCK_DGRAM , 0 );

if (! $socket )

die( 'Unable to create AF_UNIX socket' );



$server_side_sock = dirname ( __FILE__ ). "/server.sock" ;

if (! socket_bind ( $socket , $server_side_sock ))

die( "Unable to bind to $server_side_sock " );



while( 1 ) {

if (! socket_set_block ( $socket ))

die( 'Unable to set blocking mode for socket' );

$buf = '' ;

$from = '' ;

echo "Ready to receive...

" ;

$bytes_received = socket_recvfrom ( $socket , $buf , 65536 , 0 , $from );

if ( $bytes_received == - 1 )

die( 'An error occured while receiving from the socket' );

echo "Received $buf from $from

" ;



$buf .= "->Response" ; if (! socket_set_nonblock ( $socket ))

die( 'Unable to set nonblocking mode for socket' );

$len = strlen ( $buf );

$bytes_sent = socket_sendto ( $socket , $buf , $len , 0 , $from );

if ( $bytes_sent == - 1 )

die( 'An error occured while sending to the socket' );

else if ( $bytes_sent != $len )

die( $bytes_sent . ' bytes have been sent instead of the ' . $len . ' bytes expected' );

echo "Request processed

" ;

}

?>



'Client' code

<?php

if (! extension_loaded ( 'sockets' )) {

die( 'The sockets extension is not loaded.' );

}

$socket = socket_create ( AF_UNIX , SOCK_DGRAM , 0 );

if (! $socket )

die( 'Unable to create AF_UNIX socket' );



$client_side_sock = dirname ( __FILE__ ). "/client.sock" ;

if (! socket_bind ( $socket , $client_side_sock ))

die( "Unable to bind to $client_side_sock " );



if (! socket_set_nonblock ( $socket ))

die( 'Unable to set nonblocking mode for socket' );

$server_side_sock = dirname ( __FILE__ ). "/server.sock" ;

$msg = "Message" ;

$len = strlen ( $msg );

$bytes_sent = socket_sendto ( $socket , $msg , $len , 0 , $server_side_sock );

if ( $bytes_sent == - 1 )

die( 'An error occured while sending to the socket' );

else if ( $bytes_sent != $len )

die( $bytes_sent . ' bytes have been sent instead of the ' . $len . ' bytes expected' );



if (! socket_set_block ( $socket ))

die( 'Unable to set blocking mode for socket' );

$buf = '' ;

$from = '' ;

$bytes_received = socket_recvfrom ( $socket , $buf , 65536 , 0 , $from );

if ( $bytes_received == - 1 )

die( 'An error occured while receiving from the socket' );

echo "Received $buf from $from

" ;



socket_close ( $socket );

unlink ( $client_side_sock );

echo "Client exits

" ;

?>