View previous topic :: View next topic |
Author |
Message |
-=GGW=- $ol!d $n4>|e Veteran
Joined: 12 Apr 2004 Posts: 1616 Location: USA
|
Posted: Mon Nov 14, 2005 5:17 am Post subject: how to use nanosleep in linux |
|
|
hi, i'd just like to have my program sleep for a quarter of a second, doing animation for a opengl class, i've read a bunch about sleep and nanosleep and don't understand how to use them or how to declair a spec timespec tv, can some please give me a sample call to sleep for a half a second using nanosleep in c++ |
|
Back to top |
|
|
-=GGW=- $ol!d $n4>|e Veteran
Joined: 12 Apr 2004 Posts: 1616 Location: USA
|
Posted: Mon Nov 14, 2005 5:22 am Post subject: |
|
|
yay, found usleep() which takes in an int of miliseconds... ah
would still like to know how to use nanosleep if anyone has the time though |
|
Back to top |
|
|
DaveArb Guru
Joined: 29 Apr 2004 Posts: 510 Location: Texas, USA
|
Posted: Mon Nov 14, 2005 3:29 pm Post subject: |
|
|
C, not C++. Hopefully the translation would be easy for anyone knowing C++, but I don't.
nanotest.c:
Code: | #include <stdio.h>
#define _POSIX_C_SOURCE 199309
#include <time.h>
int main( void )
{
struct timespec sleepfor;
struct timespec remaining;
int returnval;
sleepfor.tv_sec = 0;
sleepfor.tv_nsec = 500000000;
printf( "begin nanosleep\n" );
returnval = nanosleep( &sleepfor, &remaining );
if ( returnval == -1 )
printf("nanosleep returned with error or was interrupted\n" );
else
printf( "ended nanosleep\n" );
} |
This program lacks error checking. On the "error or was interrupted" line, you should check errno. If it is EINTR, nanosleep was interrupted by another signal, and the remaining time you asked to sleep is in remaining.
Note that contrary to its name and parameter, nanosleep does not give you nanosecond resolution. From the documentation, it appears that 10ms on i386 is the resolution.
Compiling this program gives a warning for redefining _POSIX_C_SOURCE. This is nonetheless asked for in the man page, so I've left it in. My experience is that compliance with the documentation is a Good Idea.
Dave |
|
Back to top |
|
|
|
|
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum
|
|