Hi!

In my program I have two threads (among other things) that are used to exchange data between two machines. One thread sends and the other receives data. The connection is established correctly and the streaming exists. The problem is when one machine shuts down the socek used for communication (shutdown() + close()). On the other machine, the thread that receives data exits normally (recv() call returns zero), but send thread just crashes (or something like that) and the wholy application exits without any error message, though some code should be executed.

So, my question is how to detect in a proper manner that the peer socket was closed? This way I could manage to exit my thread normally and handle this situation.

I tried to see if send returns zero, but this is not a solution (at least as I could see, though I'm just a newbie to all this).

Here is the sorce code of the two threads.


void* send_voice(void* arg) {
voice_params* params = (voice_params*) arg;
uint8_t packet[BUFFER_SIZE];
fd_set rfds;
int ret, nHook;

pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);

printf("Starting voice transmition on socket 0x%X\n", params->com_sock);

while (1) {
FD_ZERO(&rfds);
FD_SET(params->fd, &rfds);

select(params->fd + 1, &rfds, NULL, NULL, NULL);

if (FD_ISSET(params->fd, &rfds)) {
ret = read(params->fd, packet, sizeof(packet));
if (ret > 0) {
ret = send(params->com_sock, packet, ret, 0);
if (ret <= 0) {
printf("SEND: peer socket shut down...exiting\n");
break;
}
}
else {
printf("Device error!\n");
exit(-1);
}
}

ioctl(params->fd, PHONE_HOOKSTATE, &nHook);
if (nHook == HOOK_ON)
break;
}
}

void* receive_voice (void* arg) {
voice_params* params = (voice_params*) arg;
uint8_t packet[BUFFER_SIZE];
int ret, nHook;

pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);

printf("Starting voice reception on socket 0x%X\n", params->com_sock);

while (1) {
ret = recv(params->com_sock, packet, sizeof(packet), 0);
if (ret > 0) {
ret = write(params->fd, packet, ret);
if (ret < 0) {
printf("Device error!\n");
exit(-1);
}
}
else {
printf("RECV: peer socket shut down...exiting\n");
break;
}

ioctl(params->fd, PHONE_HOOKSTATE, &nHook);
if (nHook == HOOK_ON)
break;
}
}