停止从stdin读取

Abr*_*ile 2 c++ stdin timer console-application

我在LInux/C++中编写一个简单的控制台应用程序,它接受来自命令行的用户输入.我std::getline( std::cin ) / std::cin >> text在线程中使用.

10秒后我想停止接受控制台输入并写一条短信然后做其他事情.我正在为计时器使用一个单独的线程.

这种方法不起作用,因为我无法检查在用户未插入任何文本之前已经过了10秒.

有没有更好的方法来阻止应用程序接受文本并转到另一条线?我正在考虑使用settimer和发出编程信号,但为了简单起见,我希望能从不同的线程调用.

问候

AFG

小智 5

您可以使用ncurses,或者如果您不想,可以使用此博客文章中所述的select .基本上,您可以使用select并指定超时.如果设置了stdin FD,那么您可以安全地读取它并且不会阻塞.如果您想了解更多关于选择的信息,请查看此内容,当然还有维基百科.知道这是一个方便的电话.例如,

// if != 0, then there is data to be read on stdin

int kbhit()
{
    // timeout structure passed into select
    struct timeval tv;
    // fd_set passed into select
    fd_set fds;
    // Set up the timeout.  here we can wait for 1 second
    tv.tv_sec = 1;
    tv.tv_usec = 0;

    // Zero out the fd_set - make sure it's pristine
    FD_ZERO(&fds);
    // Set the FD that we want to read
    FD_SET(STDIN_FILENO, &fds); //STDIN_FILENO is 0
    // select takes the last file descriptor value + 1 in the fdset to check,
    // the fdset for reads, writes, and errors.  We are only passing in reads.
    // the last parameter is the timeout.  select will return if an FD is ready or 
    // the timeout has occurred
    select(STDIN_FILENO+1, &fds, NULL, NULL, &tv);
    // return 0 if STDIN is not ready to be read.
    return FD_ISSET(STDIN_FILENO, &fds);
}
Run Code Online (Sandbox Code Playgroud)

另请参阅使用pthreads查看Peek stdin的 SO问题