PMH
PMH

Reputation: 73

How does FD_ISSET work?

The man page says that FD_ISSET check whether the socket is in the set. So, I think that the condition if (FD_ISSET(STDIN, &readfds)) should print out immediately if stdin is in set, but it actually waits until I hit enter. What do I miss here? is that true stdin has been already set when the program calls FD_SET(STDIN, &readfds)?

why if I enter other character rather than the enter key, the console returns command not found? I thought the character should be treated as any other character entered when I can fgets for example.

#include <stdio.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>

#define STDIN 0  // file descriptor for standard input

int main(void)
{
    struct timeval tv;
    fd_set readfds;

    tv.tv_sec = 2;
    tv.tv_usec = 500000;

    FD_ZERO(&readfds);
    FD_SET(STDIN, &readfds);

    // don't care about writefds and exceptfds:
    select(STDIN+1, &readfds, NULL, NULL, &tv);

    if (FD_ISSET(STDIN, &readfds))
        printf("A key was pressed!\n");
    else
        printf("Timed out.\n");

    return 0;
}

Upvotes: 5

Views: 15688

Answers (1)

resultsway
resultsway

Reputation: 13310

Select will wait for an enter or timeout. You feel FD_ISSET is waiting for enter because the select timedout.

You will understand better if you check for retval

struct timeval tv; 
fd_set readfds;
int retval;

tv.tv_sec = 2;
tv.tv_usec = 500000;

FD_ZERO(&readfds);
FD_SET(STDIN, &readfds);

// don't care about writefds and exceptfds:
printf ("before select \n" );
retval = select(STDIN+1, &readfds, NULL, NULL, &tv);
printf ("after select \n" );

if (retval == -1) 
    perror("select()");
else if (retval > 0)
{
    //if (FD_ISSET(STDIN, &readfds));
        printf("Data is available now.\n");
}   
else
    printf("No data . timedout \n");

Upvotes: 3

Related Questions