yotamoo
yotamoo

Reputation: 5452

Using select to detect keyboard input

I am writing a simple server using select to monitor multiple sickets.

Here's my code:

while (1) { /* Main server loop - forever */
    build_select_list();
    timeout.tv_sec = 1;
    timeout.tv_usec = 0;

    readsocks = select(maxSock+1, &socks, (fd_set *) 0, (fd_set *) 0, &timeout);

    if (readsocks < 0) {
        perror("select");
        exit(EXIT_FAILURE);
    }
    if (readsocks == 0) {
        printf(".");
        fflush(stdout);
    } else
        read_socks();
}

I know select detecs changes in the sockets it is monitoring and "report" about it. Can I detect a keyboard input from the user (for commands like exit) by using select? If not, how do I do this?

Upvotes: 0

Views: 1536

Answers (1)

Woodrow Douglass
Woodrow Douglass

Reputation: 2655

You can use STDIN_FILENO (from unistd.h), or use fileno(stdin) (from stdio.h), to get the file descriptor of the console input. Add that to your 'read' fdset, and select will "do the right thing", indicating when there's console input available. From there, just read from it like any other file descriptor.

Upvotes: 3

Related Questions