I have TCP/IP server running under embedded linux:
int sId = socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, 0);
sockaddr_in servAddr;
servAddr.sin_family = AF_INET;
servAddr.sin_addr.s_addr = htonl(INADDR_ANY);
servAddr.sin_port = htons(5000);
bind(sId, (sockaddr*)(&servAddr), sizeof(servAddr));
listen(sId, 10);
int cId = accept(sId, NULL, NULL);
After executing the code above I can receive messages from client with read() and send the responses with write(). For example like that:
for (;;)
{
int c = std::cin.get();
switch(c)
{
case 'q': break;
case 'r': recv(cId, /*...*/ , MSG_DONTWAIT); // I skip the code responsible for displaying the message
case 'w': write(cId, ... // as above
}
}
As long as the client is connected, everything is fine. The problem start when client disconnects and I try to send a message to it. When I call write() for the first time after disconnecting it returns success, and when I call it second time the program quits without error.
Is there some smart way to detect such error?
PS. I addded simplified code to present the problem. In created program, receiving messages and sending replies is implemented in separate threads. That's why I'm looking for something that would allow me to detect error when calling write().