有没有用C替代睡眠功能为毫秒? [英] Is there an alternative sleep function in C to milliseconds?

查看:262
本文介绍了有没有用C替代睡眠功能为毫秒?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些源$ C ​​$ C,它是在Windows编译。我将其转换成在Red Hat Linux上运行。

源$ C ​​$ C收录了< WINDOWS.H> 头文件和程序员使用了睡眠()函数等待一段毫秒。这会不会在Linux工作。

不过,我可以使用睡眠时间(秒)的功能,但在几秒钟内使用整数。我不想毫秒转换为秒。有没有办法,我可以在Linux上的gcc编译?

使用一个替代的睡眠功能
解决方案

是 - 老年 POSIX标准定义的 usleep()函式 ,所以这是可在Linux上:


  INT usleep(useconds_t USEC);


  
  

说明


  
  

该usleep()函式函数暂停调用进程执行
         (至少)微秒微秒。睡眠可稍微被延长
         花在处理的通话或任何系统活动或时间
         系统计时器粒度。


usleep()函式需要的微秒,所以你将有1000,以毫秒为单位睡觉乘以输入。


usleep()函式此后一直去precated并随后从POSIX删除;新的code, 了nanosleep() 是preferred:


 的#include<&time.h中GT;   INT了nanosleep(const的结构的timespec * REQ,结构的timespec * REM);


  
  

说明


  
  

了nanosleep()挂起调用线程的执行,直到至少在指定的时间 * REQ 有已过,或
  的信号的传送触发一个处理程序的调用中
  调用线程或结束处理。


  
  

的timespec用于指定的时间用纳秒precision间隔的结构。它定义如下:

 结构的timespec {
           time_t的tv_sec; / *秒*的/
           长tv_nsec; / * *纳秒/
       };


I have some source code that was compiled on Windows. I am converting it to run on Red Hat Linux.

The source code has included the <windows.h> header file and the programmer has used the Sleep() function to wait for a period of milliseconds. This won't work on the Linux.

However, I can use the sleep(seconds) function, but that uses integer in seconds. I don't want to convert milliseconds to seconds. Is there a alternative sleep function that I can use with gcc compiling on Linux?

解决方案

Yes - older POSIX standards defined usleep(), so this is available on Linux:

   int usleep(useconds_t usec);

DESCRIPTION

The usleep() function suspends execution of the calling process for (at least) usec microseconds. The sleep may be lengthened slightly by any system activity or by the time spent processing the call or by the granularity of system timers.

usleep() takes microseconds, so you will have to multiply the input by 1000 in order to sleep in milliseconds.


usleep() has since been deprecated and subsequently removed from POSIX; for new code, nanosleep() is preferred:

   #include <time.h>

   int nanosleep(const struct timespec *req, struct timespec *rem);

DESCRIPTION

nanosleep() suspends the execution of the calling thread until either at least the time specified in *req has elapsed, or the delivery of a signal that triggers the invocation of a handler in the calling thread or that terminates the process.

The structure timespec is used to specify intervals of time with nanosecond precision. It is defined as follows:

       struct timespec {
           time_t tv_sec;        /* seconds */
           long   tv_nsec;       /* nanoseconds */
       };

这篇关于有没有用C替代睡眠功能为毫秒?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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