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
.
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.
CodePudding user response:
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);