How to implement timeout for getline()?

c++, centos, gcc

Solution

How about:

/* Wait 5 seconds. */
alarm(5);

/* getline */

/* Cancel alarm. */
alarm(0);

Alternatively you could use `setitimer`.

As R. Martinho Fernandes requested:

The function `alarm` arranges for the current process to receive a SIGALRM in 5 seconds from its call. The default action for a `SIGALRM` si to terminate the process abnormally. Calling `alarm(0)` disables the timer.

Problem

I want to read a string from command line through `getline()` in c++. For that I want to add a timer of `5` sec. If no string read, then the program will terminate. How can I do this?

Original source

Related problems