首页 > 解决方案 > c ++ usleep在linux上立即返回

问题描述

简单用法:

#include <unistd.h>
#include <iostream>

int main()
{   
    std::cout << usleep(20 * 1000) << std::endl;

    return 0;
}

编译g++ main.cpp。可执行退出立即打印0指示未检测到错误。那么有什么问题呢?

标签: c++

解决方案


实际上,您传递给 usleep() 的参数以微秒为单位。所以在 20 毫秒内程序退出..您可以传递 20 *1000000 或者您可以使用 chrono 库。

#include <iostream>       // std::cout, std::endl
#include <thread>         // std::this_thread::sleep_for
#include <chrono>         // std::chrono::seconds

int main() 
{
  std::cout << "countdown:\n";
  for (int i=10; i>0; --i) {
    std::cout << i << std::endl;
    std::this_thread::sleep_for (std::chrono::seconds(1));
  }
  std::cout << "Lift off!\n";

  return 0;
}

推荐阅读