好的,等待5秒,terminate如果没有输入:
#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';
}
Run Code Online (Sandbox Code Playgroud)
怎么样:
/* Wait 5 seconds. */
alarm(5);
/* getline */
/* Cancel alarm. */
alarm(0);
Run Code Online (Sandbox Code Playgroud)
或者你可以使用setitimer.
正如R. Martinho Fernandes所要求的:
该函数alarm安排当前进程在调用后 5 秒内接收 SIGALRM。SIGALRMsi 异常终止进程的默认操作。调用alarm(0)会禁用计时器。
| 归档时间: |
|
| 查看次数: |
3800 次 |
| 最近记录: |