Question

I have this:

    #define STDIN 0 

    char buffer[512];
    bzero(buffer,512);
    struct sockaddr_in from;
    string input;
    RoutingMessage parser;

    cout << "Listening...\n";

        /* Temporary fix. 
    /* This should be abstracted, and more widely used
    /********* Start Select() ***********/
    fd_set readfds;
    struct timeval tv;
    tv.tv_sec = 120;
    tv.tv_usec = 0; //wait for 1.5 second here

    int rv = 1;

    // clear the set ahead of time
    FD_ZERO(&readfds);

    // add our descriptors to the set
    FD_SET(mySocket, &readfds);
    FD_SET(STDIN, &readfds);

    // the n param for select()
    int n = mySocket + 1;
    /********* End Select() ***********/

    while(rv != 0)
    {
        rv = select(n, &readfds, NULL, NULL, &tv);

        if (rv == -1)
            perror("select"); // error occurred in select()

        if (FD_ISSET(STDIN, &readfds))
        {
                cin >> input;
                cout << input << endl;
        }
        else
        {
            bzero(buffer,512);
            int n = recvfrom(mySocket,buffer,512,0,(struct sockaddr *)&from, &sockLen);

            if (n < 0) 
                perror("recvfrom");

            if (n > 0)
            {
                parser.ParseMessage(buffer, fromNode, messages);
                ProcessMessages();
            }
         }
    }

However, when I try to type anything in my program, I don't get the response from cout:

Listening...
3702 has converged!
3701 has converged!
3703 has converged!
test
// blank line

Am I doing something wrong?

Was it helpful?

Solution

select alters the readfds you pass in to it. You'll have to provide the file descriptors you want to watch for events each time you call select. e.g.

while(rv != 0) {
  FD_ZERO(&readfds);
  FD_SET(mySocket, &readfds);
  FD_SET(STDIN, &readfds);
  rv = select(n, &readfds, NULL, NULL, &tv);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top