递归遍历目录时 C 中的 gmtime 不一致

Inconsistent gmtime in C when recursively traversing directories

我有一个 C 程序,我在其中使用遍历目录结构的递归函数。它需要一个 time_t 变量并从中创建一个 gmtime 结构。

递归dir函数来自How to recursively list directories in C on Linux?

void traversedir(time_t cutoff, const char* name, int indent)
{
    if (indent > 9)
        return;

    DIR* dir;
    struct dirent* entry;

    if (!(dir = opendir(name)))
        return;

    struct tm *t = gmtime(&cutoff);
    printf("%d-%d-%d %d:%d:%d (%lld)\n", (1900 + t->tm_year), (t->tm_mon + 1), t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec, (long long) cutoff);
    sleep(1);  // only for debugging

    while ((entry = readdir(dir)) != NULL) {
        if (entry->d_type == DT_DIR) {
            char path[1024];
            if (entry->d_name[0] == '.' && !isValidNumber(entry->d_name))
                continue;
            snprintf(path, sizeof(path), "%s/%s", name, entry->d_name);

            ...

            traversedir(cutoff, path, indent + 2);
        }
    }
    closedir(dir);
}

void imageCleanup()
{
    time_t cutoff = (time(NULL) - (86400 * 10));
    do {
        printf("Cutoff: %lld\n", (long long) cutoff);
        traversedir(cutoff, "/path/to/dir", 0);
        sleep(2);
        cutoff += 3600;
    } while (!available_storage() && cutoff < time(NULL));
}

这是运行程序时的输出。

Cutoff: 1534245930
2018-8-14 11:25:30 (1534245930)
2018-8-24 11:25:31 (1534245930)
2018-8-14 11:25:30 (1534245930)
2018-8-24 11:25:33 (1534245930)
2018-8-14 11:25:30 (1534245930)
2018-8-14 11:25:35 (1534245930)
2018-8-14 11:25:30 (1534245930)
2018-8-14 11:25:30 (1534245930)
2018-8-24 11:25:38 (1534245930)
2018-8-14 11:25:30 (1534245930)
2018-8-14 11:25:30 (1534245930)
2018-8-14 11:25:30 (1534245930)
2018-8-14 11:25:30 (1534245930)
2018-8-24 11:25:43 (1534245930)
2018-8-14 11:25:30 (1534245930)
2018-8-14 11:25:30 (1534245930)
2018-8-14 11:25:30 (1534245930)
2018-8-14 11:25:30 (1534245930)
2018-8-14 11:25:30 (1534245930)
2018-8-14 11:25:30 (1534245930)
2018-8-14 11:25:30 (1534245930)
2018-8-14 11:25:30 (1534245930)
2018-8-24 11:25:52 (1534245930)
2018-8-14 11:25:30 (1534245930)
2018-8-24 11:25:54 (1534245930)
2018-8-14 11:25:55 (1534245930)
2018-8-24 11:25:56 (1534245930)
2018-8-14 11:25:30 (1534245930)
2018-8-24 11:25:58 (1534245930)

time_t结构体转换而来的time_t在括号内。它始终是 1534245930 或 2018 年 8 月 14 日 11:25:30 上午,即程序执行时的负十天。

您可以看到转换非常不一致。数次秒数跟在执行时的实际时间之后。日子也变了几次。

有人知道或知道是什么原因造成的吗?我试过只做一个简单的循环来转换静态 time_t 而没有任何问题,所以我只能假设它有一些东西要

仔细阅读time(7) and gmtime(3).

请注意 gmtime 不是 reentrant since it returns the address of some static data. You want gmtime_r (since your traversedir function is recursive) and should use a local struct tm automatic variable

所以

struct tm mytm;
struct tm *t = gmtime_r(&cutoff, &mytm);

然后 t 将指向 call stack 上的 mytm(而不是某些静态数据)。

您还应该使用 strftime(3)(同样,将足够大的缓冲区声明为自动变量,或一些堆分配的缓冲区)。

您可能也对 nftw(3) and stat(2) 感兴趣。

另请阅读 How to debug small programs