简体   繁体   中英

sleep() C doesn't return the correct value

I am a doing a school project (need to develop it in C) and I need it to execute some code each X seconds and Y seconds after the execution of the program has started it must end.

So I wrote:

alarm(Y);
s=X;
while(!end){
    s = sleep(s); //because it generates some children that send signal to him and in that case i need to do other stuffs
    if(s == 0){
        //code to do each X seconds
    }
}

The variable end is a global variable initialized at 0 and when a SIGALARM is received the value becomes 1.

If I have got X>Y the code to do each X seconds shouldn't be executed but if X=Y+1 it is executed once.

Could you tell me why this happens?

Per the manual :

DESCRIPTION

sleep() causes the calling thread to sleep either until the number of real-time seconds specified in seconds have elapsed or until a signal arrives which is not ignored.

RETURN VALUE

Zero if the requested time has elapsed, or the number of seconds left to sleep, if the call was interrupted by a signal handler.

Your use of alarm() almost certainly interrupts your sleep() call.

And even if alarm() didn't interfere, sleep() can always be interrupted by a signal anyway, and you have to handle that appropriately.

This is easy to do with only sleep() :

#include <stdio.h>
#include <unistd.h>

int main(void) {
  unsigned int const y = 5;
  unsigned int const x = 2;

  {
    unsigned int left = y;
    unsigned int action = 0;
    while (left > 0) {
      unsigned int time = x - action < left ? x - action : left;
      printf("I will sleep for %u\n", time);
      {
        unsigned ret = sleep(time);

        action += time - ret;
        if (action >= x) {
          printf("do something\n");
          action -= x;
        }

        left -= time - ret;
      }
    }
  }
}

But note that it's clearly not accurate, there is better method that sleep() with POSIX standard like clock_gettime() and nanosleep() or clock_nanosleep() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM