Hi all,

I have a multithreaded program, one of the threads needs to listen for user input. I was wondering is there a way of checking for user input every few seconds or milliseconds, without having the thread hang on a fgets() function?

Current I have:

while(keep_running == TRUE) {
    usleep(25);
    char command[80];
    fgets(command,80,stdin);
    /* handle input */
}

I want to change fgets(command,80,stdin); to something that checks for users input and not waits on user input.

If you are planning for multi threading then why not let a thread wait for user input ?

oh is there some sort of function to do this? Sorry not totally sure what you mean.

No what I meant was... You are any way going to spawn multiple thread so what is the problem is one of the threads wait for the user input (in other words why exactly do you not want to use fgets)

I don't know, it seems like the right way to do it (using fgets). But I'm doing an assignment and it says on the assignment sheet that you can check every 25 milliseconds for user input. Which sounds to me like they want the thread to continue running and not get stuck on something like fgets.

ps. I know usleep() is in microseconds, I will fix that later.

I don't know, it seems like the right way to do it (using fgets). But I'm doing an assignment and it says on the assignment sheet that you can check every 25 milliseconds for user input. Which sounds to me like they want the thread to continue running and not get stuck on something like fgets.

ps. I know usleep() is in microseconds, I will fix that later.

try read() system call [if you are using linux]
stdin is opened in O_NONBLOCK mode. so it will not wait block,
it will return -1 if there is no data ..

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.