Home > Software design >  Sleep program for half a second in C on Linux
Sleep program for half a second in C on Linux

Time:12-01

I just can't find a way to sleep my program or just make it wait for a set amount of miliseconds, I tried sleep() but it only works for full seconds, usleep() is giving implicit declaration error and correcting it to sleep(), nanosleep() also only pauses it for full seconds.

while(1){
        wclear(win);
        box(win, 0, 0);
        mvwprintw(win, 0, anim, "Snake");
        wrefresh(win);

        sleep(500);

        if(intro == 3){
            if(anim < 53) anim  ;
            else intro--;
        }
        if(intro == 2){
            if(anim > 2) anim--;
            else intro--;
        }
        if(intro == 1){
            if(anim < 23) anim  ;
            else intro--;
        }
        if(intro == 0) break;
    }

All I want is to make a smooth little animation, but no matter what library I use or what kind of sleep function I use, it will either do full seconds which is too long, or 0 seconds (so nothing), or throw errors.

CodePudding user response:

Here are some ideas to explore why usleep isn't working out. select is another popular way to delay for periods of time.

#include <unistd.h>
int main( )
{
  int i;
  for ( i = 0 ; i < 10 ; i   ) usleep(100000);
  return 0;
}

Also, try using the compiler to reveal where unistd.h is coming from, like this for gcc

gcc -H main.c 
. /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/unistd.h
. . . MORE . . .

Another helping idea is to output the preprocessor output like this:

gcc -E main.c 

# 1 "main.c"
# 1 "<built-in>" 1
# 1 "<built-in>" 3
# 370 "<built-in>" 3
# 1 "<command line>" 1
# 1 "<built-in>" 2
# 1 "main.c" 2
# 1 "/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/unistd.h" 1 3 4
# 71 "/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/unistd.h" 3 4

. . . MORE . . .

Here is some code that uses select to create a timeout.

#include <unistd.h>
#include <stdio.h>
int main( )
{
  fd_set set;
  struct timeval timeout;
  FD_ZERO(&set);
  timeout.tv_sec = 0;
  timeout.tv_usec = 100000;
  if (0==select(FD_SETSIZE, &set, NULL, NULL, &timeout)) printf("timeout\n");

  return 0;
}
  • Related