Reputation: 151
I have a UNIX domain socket and I am able to create and communicate between the server and client. The problem is the scenario where a server may crash unexpectedly: How to handle such situation?
The client in my code is part of a different program which also manages various other tasks and sends the data to server via socket.
The return error value is an Enum maintained by me. This code is part of a library.
I connect to server as below
int sock;
struct sockaddr_un server;
//Create socket
sock = socket(AF_UNIX , SOCK_STREAM , 0);
if (sock == -1)
{
return ERR_SOCK;
}
server.sun_family = AF_UNIX;
strcpy(server.sun_path,SOCKET_PATH);
//Connect to remote server
if (connect(sock , (struct sockaddr *)&server , sizeof(struct sockaddr_un)) < 0)
{
return ERR_CONFAIL;
}
After this I send the data as below
ret=send(sock , message , sizeof(struct message_t) , 0 );
if(ret < 0){
printf("Error while sending\n");
return ERR_NOCON;
}
Normally everything works fine but if I terminate my server and send the data, then send does not return and the client terminates.
Upvotes: 1
Views: 805
Reputation: 1
You could use poll(2) on the file descriptor before writing or sending on it. This would check that data can be sent. More generally, you could have (and perhaps already have) some event loop.
As Dark Falcon commented (see this answer), you are getting the SIGPIPE
signal. So read signal(7). You could ignore that signal (but they are pro and cons in ignoring SIGPIPE
).
Use also strace(1) to understand a bit more what is happening (what syscalls and signals are involved).
You might also have the server send its pid, and have the client use kill(2) with a 0 signal number to test the existence of the server's process (since both are local to the same machine). But I won't recommend that in your case.
Perhaps read Advanced Linux Programming.
Upvotes: 2