I have a problem. I recently started with daemon and sockets. My current setup consists of a daemon that creates a socket and a client that writes messages and reads the processed response.
Well, read the answer.
The daemon demonizes itself, creates a socket, and even processes the message (I can check through the log entries that I make), but as soon as I try to send a response to the client, the daemon is blocked; the client never receives a response, and if I am a ctrl-cclient, the daemon also shuts down.
This is a completely strange behavior for me, and I can’t explain what is happening, so I ask you for any hints.
Brief summary:
- the type of socket AF_UNIX, therefore local and non-connected networks - The daemon successfully receives a message, but cannot write back - the client cannot read (since the send()server is blocked) and if I am a ctrl-cclient, the daemon also exits (but this signal is not sent to the daemon )
Below is my code, divided into an interesting and non-working part.
Thanks a lot in advance for tips, help and suggestions!
UPDATE:
Client code added!
int main()
{
createSocket();
daemonize();
FILE *client_fd;
int fd;
socklen_t len;
string tmp;
char *buf = new char[1024];
while(1)
{
struct sockaddr_un saun;
len = sizeof(saun);
if((fd = accept(m_socket, (sockaddr*)&saun, &len)) < 0)
{
writeLog("Accepting connection failed!");
continue;
}
client_fd = fdopen(fd, "r");
if(client_fd == NULL)
{
writeLog("fdopen() failed!");
continue;
}
while(fgets(buf, bufferSize, client_fd) != NULL)
{
writeLog(buf);
tmp = evaluateMsg(buf);
writeLog(tmp);
if(send(fd, (tmp + "\n").c_str(), tmp.size() + 1, 0) < 0)
{
writeLog("Could not write message back!");
continue;
}
else
writeLog("bytes written!");
}
close(fd);
}
}
Below is the customer code:
int main()
{
int sockfd;
sockaddr_un addr;
sockfd = socket(AF_UNIX, SOCK_STREAM, 0);
addr.sun_family = AF_UNIX;
strcpy(addr.sun_path, SOCKET_PATH);
if(connect(sockfd, (sockaddr*)&addr, sizeof(addr)) < 0)
{
cerr<<"Connection failed!"<<endl;
exit(1);
}
write(sockfd, "hello", 5);
char *buf = new char[1024];
FILE *fd = fdopen(sockfd, "r");
fgets(buf, 1024, fd);
cout<<buf<<endl;
close(sockfd);
}