text
stringlengths
0
234
.in +4n
.ex
void *addrp;
addrlen = sizeof(struct sockaddr_un);
addrp = malloc(addrlen + 1);
if (addrp == null)
/* handle error */ ;
memset(addrp, 0, addrlen + 1);
if (getsockname(sfd, (struct sockaddr *) addrp, &addrlen)) == \-1)
/* handle error */ ;
printf("sun_path = %s\en", ((struct sockaddr_un *) addrp)\->sun_path);
.ee
.in
.pp
this sort of messiness can be avoided if it is guaranteed
that the applications that
.i create
pathname sockets follow the rules outlined above under
.ir "pathname sockets" .
.sh examples
the following code demonstrates the use of sequenced-packet
sockets for local interprocess communication.
it consists of two programs.
the server program waits for a connection from the client program.
the client sends each of its command-line arguments in separate messages.
the server treats the incoming messages as integers and adds them up.
the client sends the command string "end".
the server sends back a message containing the sum of the client's integers.
the client prints the sum and exits.
the server waits for the next client to connect.
to stop the server, the client is called with the command-line argument "down".
.pp
the following output was recorded while running the server in the background
and repeatedly executing the client.
execution of the server program ends when it receives the "down" command.
.ss example output
.in +4n
.ex
$ \fb./server &\fp
[1] 25887
$ \fb./client 3 4\fp
result = 7
$ \fb./client 11 \-5\fp
result = 6
$ \fb./client down\fp
result = 0
[1]+ done ./server
$
.ee
.in
.ss program source
\&
.ex
/*
* file connection.h
*/
#define socket_name "/tmp/9lq7bnbnbycd6nxy.socket"
#define buffer_size 12
/*
* file server.c
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#include "connection.h"
int
main(int argc, char *argv[])
{
struct sockaddr_un name;
int down_flag = 0;
int ret;
int connection_socket;
int data_socket;
int result;
char buffer[buffer_size];
/* create local socket. */
connection_socket = socket(af_unix, sock_seqpacket, 0);
if (connection_socket == \-1) {
perror("socket");
exit(exit_failure);
}
/*
* for portability clear the whole structure, since some
* implementations have additional (nonstandard) fields in
* the structure.
*/