Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Result of time() not updated after sleep()

I’m trying to pause my program for 1 second, and check the system time after that (I’m on Linux)

This is my testing program:

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

int main() {

    time_t now = time(NULL);
    struct tm *time_now = localtime(&now);
    printf("now: %d-%d\n", time_now->tm_min, time_now->tm_sec);

    int i = 0;
    for (; i < 5; i++) {
        sleep(1);
    }
    // This printf result is not as expected
    printf("now: %d-%d\n", time_now->tm_min, time_now->tm_sec);

    return 0;
}

The expected result is that the second printf would print +5 seconds. Instead, it prints the same time/seconds as the first printf.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I’ve found (maybe) the same problem posted here, but it doesn’t seem to work:
sleep() and time() not functioning as expected inside for loop.

Sorry for my bad english, and thank you for your time.

>Solution :

Code is printing the original *time_now values – as expected.

Simply read time again to use new values.

time_t now = time(NULL);
struct tm *time_now = localtime(&now);
printf("now: %d-%d\n", time_now->tm_min, time_now->tm_sec);

int i = 0;
for (; i < 5; i++) {
    sleep(1);
}

// Add
time_t now = time(NULL);
struct tm *time_now = localtime(&now);

printf("now: %d-%d\n", time_now->tm_min, time_now->tm_sec);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading