Gentoo Forums
Gentoo Forums
Gentoo Forums
Quick Search: in
how to use nanosleep in linux
View unanswered posts
View posts from last 24 hours

 
Reply to topic    Gentoo Forums Forum Index Portage & Programming
View previous topic :: View next topic  
Author Message
-=GGW=- $ol!d $n4>|e
Veteran
Veteran


Joined: 12 Apr 2004
Posts: 1616
Location: USA

PostPosted: Mon Nov 14, 2005 5:17 am    Post subject: how to use nanosleep in linux Reply with quote

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
View user's profile Send private message
-=GGW=- $ol!d $n4>|e
Veteran
Veteran


Joined: 12 Apr 2004
Posts: 1616
Location: USA

PostPosted: Mon Nov 14, 2005 5:22 am    Post subject: Reply with quote

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
View user's profile Send private message
DaveArb
Guru
Guru


Joined: 29 Apr 2004
Posts: 510
Location: Texas, USA

PostPosted: Mon Nov 14, 2005 3:29 pm    Post subject: Reply with quote

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
View user's profile Send private message
Display posts from previous:   
Reply to topic    Gentoo Forums Forum Index Portage & Programming All times are GMT
Page 1 of 1

 
Jump to:  
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