Sagar Mohantu
Sagar Mohantu

Reputation: 121

RFComm- client while loop does not end when server is killed

I am using RFComm socket. I have a client loop where it does read and write in a loop. When the server exits I guess , the client should also terminate. But client is not terminating. It is not printing "client loop exited". My code is as follows-

    void* clientLoop(void* arg)

{
    char* server_address = (char*)arg;
    printf("\nserver address in clientLoop = %s\n",server_address);
    struct sockaddr_rc addr = { 0 };
    int s, status;
    char gpsMessage[128];
    int flag = true;

    struct timeval tv;

    // allocate a socket
    s = socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM);

    if(s<0) perror("socket error in client loop");
    // set the connection parameters (who to connect to)
    addr.rc_family = AF_BLUETOOTH;
    addr.rc_channel = (uint8_t) 1;
    str2ba( server_address, &addr.rc_bdaddr );

    tv.tv_sec = 30; // 30 seconds
    tv.tv_usec = 0; // microsecs, set to 0 (or ...)
    setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv,sizeof(struct timeval));
    // connect to server
    status = connect(s, (struct sockaddr *)&addr, sizeof(addr));

    if(status<0) perror("socket status  error in client loop");

    // send a message
    if( status == 0 ) {
        while(flag)
        {
            sleep(10);
            printf("clientLoop did not exited\n");
            prepareMessageToSend(gpsMessage);
            status = write(s,gpsMessage , strlen(gpsMessage));
           if(status == 0) flag=false;
            status = read(s,gpsMessage, 128);
            if(strcmp(gpsMessage,"Ring"))
            {
                printf("RING\n");
                system("espeak -ven+f3 -k5 -s150 \"I've just picked up a fault in the AE35 unit\"");
            }  
           if(status == 0) flag=false;
        }
    }

    if( status < 0 ) perror("uh oh");
    printf("clientLoop exited\n");
    close(s);
   //return s;
}

Upvotes: 0

Views: 134

Answers (1)

D&#233;j&#224; vu
D&#233;j&#224; vu

Reputation: 28850

Give the socket a timeout

struct timeval tv;
tv.tv_sec = 30; // 30 seconds
tv.tv_usec = 0; // microsecs, set to 0 (or ...)
setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv,sizeof(struct timeval));

if the read cannot be performed within that time, the timeout is triggered.

Also

 status = read(s,gpsMessage, 128);
 // check status first, or if there is no ambiguity, check only the 4 first chars
 if(strncmp(gpsMessage, "Ring", 4))

(in case the message could not be set correctly)

Upvotes: 1

Related Questions