tags:

views:

1395

answers:

5

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 used in gcc compiling on Linux?

+4  A: 

Yes, usleep():

   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.

It takes microseconds so you will have to multiply by 1000.

EDIT: It appears I've led you astray, usleep() is now deprecated and nanosleep() (from time.h) is preferred. It has a more complicated calling convention - the man page has all the details.

caf
You'll have to `#include <unistd.h>`
Whisty
Hello, I looked up the usleep in the man. However, I didn't see anything to suggest that usleep() is deprecated. Where did you get that information, I am interested to read? Thanks.
robUK
My most in-reach man page says "This function is obsolete. Use nanosleep(2) or setitimer(2) instead.", but there's a lot of code out there that uses usleep() so it's not like it's going to go away. If it works for your app, then I don't see a problem using it.
caf
+2  A: 
$ man 3 usleep
greyfade
+2  A: 

Beyond usleep, the humble select with NULL file descriptor sets will let you pause with microsecond precision, and without the risk of SIGALRM complications.

sigtimedwait and sigwaitinfo offer similar behavior.

pilcrow
+1  A: 
#include unistd.h

int usleep(useconds_t useconds); //pass in microseconds`
+3  A: 

Alternatively to usleep(), which is not defined in POSIX though it is evidently available on Linux, the POSIX standard defines:

nanosleep - high resolution sleep

#include <time.h>
int nanosleep(const struct timespec *rqtp, struct timespec *rmtp);

The nanosleep() function shall cause the current thread to be suspended from execution until either the time interval specified by the rqtp argument has elapsed or a signal is delivered to the calling thread, and its action is to invoke a signal-catching function or to terminate the process. The suspension time may be longer than requested because the argument value is rounded up to an integer multiple of the sleep resolution or because of the scheduling of other activity by the system. But, except for the case of being interrupted by a signal, the suspension time shall not be less than the time specified by rqtp, as measured by the system clock CLOCK_REALTIME.

The use of the nanosleep() function has no effect on the action or blockage of any signal.

Jonathan Leffler