在 Ubuntu 中使用价值大于 1000000 的 usleep 是否安全 [英] Is it safe to use usleep in Ubuntu with value greater than 1000000

查看:30
本文介绍了在 Ubuntu 中使用价值大于 1000000 的 usleep 是否安全的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 usleep man 中看到:

EINVAL
usec is not smaller than 1000000. (On systems where that is considered an error.) 

所以我想知道在 Ubuntu 中使用价值大于 1000000 的 usleep 是否可以,如果不是(或者如果我想支持其他平台)当我需要睡眠时有什么替代方案2.2 秒(例如).

So i wonder if its ok to use usleep in Ubuntu with value greater than 1000000 and if not (or in case that i want to support other platforms ) what is the alternative when i need sleep for 2.2 sec (for example) .

谢谢.

推荐答案

为了安全起见,另一种选择是信任文档并使用循环来实现它:

One alternative is to trust the documentation and implement it using a loop just to be safe:

#define USLEEP_MAX (1000000 - 1)

void long_sleep(unsigned long micros)
{
  while(micros > 0)
  {
    const unsigned long chunk = micros > USLEEP_MAX ? USLEEP_MAX : micros;
    usleep(chunk);
    micros -= chunk;
  }
}

你还应该检查 usleep() 的返回值,为了简洁我省略了.

You should also inspect the return value of usleep(), I omitted that for brevity.

在生产中,您可以使用 Autoconf 和朋友来检测正确的 USLEEP_MAX 在编译时,如果本地系统对参数没有限制,甚至可以切换到普通包装器.可以享受数小时的乐趣.

In production, you can have fun with Autoconf and friends to detect the proper USLEEP_MAX at compile-time, and even switch to a plain wrapper if the local system doesn't have a limit for the argument. Hours of fun can be had.

这篇关于在 Ubuntu 中使用价值大于 1000000 的 usleep 是否安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆