I just wrote a program that uses local socket to communicate between two processes
if client send one message to server, and then close the connection, server would only receive one message
clent:
send(srvfd,data,size,0)
close(srvfd)
server:
n=recv(fd,buf,size,0)
however, if client send one message, and server also send one message (any string) back to client, then client close the connection, server would receive the older message that client sends
client:
send(srvfd,data,size,0)
n=recv(srvfd,buf,size,0)
close(srvfd)
server:
n=recv(fd,buf,size,0)
send(fd,"response",8,0)
n=recv(fd,buf,size,0) //receive the first message again
here is my initialize code:
struct sockaddr_un srvAddr;
int listenFd = socket(PF_UNIX, SOCK_STREAM, 0);
if (listenFd < 0) {
perror("cannot create communication socket");
throw runtime_error("cannot create communication socket");
}
srvAddr.sun_family = AF_UNIX;
strncpy(srvAddr.sun_path, sockFile.c_str(), sockFile.size());
unlink(sockFile.c_str());
int ret = bind(listenFd, (struct sockaddr*) &srvAddr, sizeof(srvAddr));
if (ret == -1) {
perror("cannot bind server socket");
close(listenFd);
unlink(sockFile.c_str());
throw runtime_error("cannot bind server socket");
}
ret = listen(listenFd, BACKLOG);
if (ret < 0) {
perror("cannot listen the client connect request");
close(listenFd);
unlink(sockFile.c_str());
throw runtime_error("cannot listen the client connect request");
}