What does setting the timeout to '-1' do for the poll()-function and how do I code a non-blocking scanf()-function?

 In C, setting the timeout to '-1' for the `poll()` function will make it behave as a blocking call, meaning it will wait indefinitely until the file descriptor(s) or events being monitored become ready.


On the other hand, if you want to code a non-blocking `scanf()` function in C, you can use a combination of functions to achieve this. The key is to ensure that the program doesn't block while waiting for input. Here's an example of how you can do this using `select()`:


```c

#include <stdio.h>

#include <stdlib.h>

#include <sys/select.h>

#include <sys/time.h>

#include <sys/types.h>


int main() {

    fd_set readfds;

    struct timeval tv;

    int ret;


    while (1) {

        // Set up the file descriptor set

        FD_ZERO(&readfds);

        FD_SET(STDIN_FILENO, &readfds);


        // Set the timeout to 0 for non-blocking behavior

        tv.tv_sec = 0;

        tv.tv_usec = 0;


        ret = select(STDIN_FILENO + 1, &readfds, NULL, NULL, &tv);


        if (ret == -1) {

            perror("select");

            exit(1);

        } else if (ret) {

            if (FD_ISSET(STDIN_FILENO, &readfds)) {

                char input[256];

                if (fgets(input, sizeof(input), stdin) != NULL) {

                    printf("You entered: %s", input);

                }

            }

        } else {

            // No input is available

            printf("No input available.\n");

        }

    }


    return 0;

}

```


In this code:


1. We use `select()` to check if input is available on `stdin` without blocking. The timeout `tv` is set to zero.


2. If `select()` returns a value greater than 0, it means input is available, and we can use `fgets()` to read the input.


3. If `select()` returns 0, it means no input is available, so you can handle this case accordingly.


This code creates a non-blocking `scanf()`-like behavior. It continuously checks for input without blocking the program's execution. You can modify the handling of available input according to your specific requirements.

Post a Comment

Previous Post Next Post