sleep() 和 time() 在 for 循环中没有按预期运行

sleep() and time() not functioning as expected inside for loop

我正在尝试创建一个 tm 结构指针数组,每个结构的 tm_sec 值比前一个大 2 秒。

#include <stdio.h>
#include <time.h>
#include <unistd.h> /* sleep() */

int main(signed int argc, char **argv) {
    struct tm *collection[5];

    for(struct tm **p = collection; p < collection + 5; p += 1) {
        sleep(2);
        const time_t timeNow = time(NULL);
        *p = gmtime(&timeNow);
    }

    for(struct tm **p = collection; p < collection + 5; p += 1) {
        if(p != collection + 4) {
            puts((**p).tm_sec == (**(p + 1)).tm_sec ? "equal" : "not equal");
        }

        puts(asctime(*p));
    }
}

执行大约持续 10 秒,这看起来不错,但结果输出是:

equal
Sat Jul 28 01:42:15 2018
equal
Sat Jul 28 01:42:15 2018    
equal
Sat Jul 28 01:42:15 2018    
equal
Sat Jul 28 01:42:15 2018    
Sat Jul 28 01:42:15 2018

在 linux64 上使用 GCC 7.3.0 编译。不知道我做错了什么。

注意:最初我在插入第一个元素时没有第一个 for 循环休眠,但为了简单起见,我在这里将其删除。没什么区别。

来自手册页:

POSIX.1-2001 says: "The asctime(), ctime(), gmtime(), and localtime() functions shall return values in one of two static objects: a broken-down time structure and an array of type char. Execution of any of the functions may overwrite the information returned in either of these objects by any of the other functions." This can occur in the glibc implementation.

对于单线程程序,只需取消引用指针:

#include <stdio.h>
#include <time.h>
#include <unistd.h> /* sleep() */

int main(signed int argc, char **argv) {
    struct tm collection[5];

    for (struct tm *p = collection; p < collection + 5; p++) {
        sleep(2);
        const time_t timeNow = time(NULL);
        *p = *gmtime(&timeNow);
    }

    for(struct tm *p = collection; p < collection + 5; p++) {
        if(p != collection + 4) {
            puts((*p).tm_sec == (*(p + 1)).tm_sec ? "equal" : "not equal");
        }

        puts(asctime(p));
    }
}

对于多线程程序,您需要使用 gmtime_rasctime_r