Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement timeout for getline()? [duplicate]

Tags:

c++

gcc

centos

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?

like image 490
Reddi Rajendra P Avatar asked Mar 20 '13 12:03

Reddi Rajendra P


2 Answers

ok, wait for 5 sec, and terminate if there was no input:

#include <thread>
#include <atomic>
#include <iostream>
#include <string>

int main()
{
    std::atomic<bool> flag = false;
    std::thread([&]
    {
        std::this_thread::sleep_for(std::chrono::seconds(5));

        if (!flag)
            std::terminate();
    }).detach();

    std::string s;
    std::getline(std::cin, s);
    flag = true;
    std::cout << s << '\n';
}
like image 98
Abyx Avatar answered Oct 22 '22 04:10

Abyx


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.

like image 36
cnicutar Avatar answered Oct 22 '22 04:10

cnicutar