c语言 - sys 函数调用"stat"更改我的文件吗?



我目前正在努力让"C"更像我自己的脚本语言。我在*.so文件中编写程序特定代码,在运行时重新加载该文件并执行我编写的新代码。

我面临的问题是函数"stat"的结果。每次我问SO文件是否已经通过"stat(filename,statbuf)"修改时,结果stat->mtim似乎总是被更改了。因此,我在每次循环运行中都会不断地重新加载代码。

我假设,如果没有文件更改为文件,则st_mtime必须始终相同。我错了吗?

这里的函数我如何检索值st_mtime:

inline timespec LinuxGetLastWriteTime(const std::string& filename) {
    struct stat *buf;
    stat(filename.c_str(), buf);
    return buf->st_mtim;
}

在这里我检查是否必须重新加载:

timespec NewSOWriteTime = LinuxGetLastWriteTime(SoSource);
if ( Game.last_modification  != NewSOWriteTime ) {
        LinuxUnloadGameCode(&Game);
        Game = LinuxLoadGameCode(SoSource, "libCode_temp.so");
}

和我的两个过载!=以及<:

bool operator<(const timespec& lhs, const timespec& rhs) {
    if (lhs.tv_sec == rhs.tv_sec)
        return lhs.tv_nsec < rhs.tv_nsec;
    else
        return lhs.tv_sec < rhs.tv_sec;
}
bool operator!=(const timespec& lhs, const timespec& rhs) {
    if (lhs.tv_sec == rhs.tv_sec)
        return lhs.tv_nsec != rhs.tv_nsec;
    else
        return lhs.tv_sec != rhs.tv_sec;

任何可能发生这种情况的想法

您使用的代码:

struct stat *buf;
stat(filename.c_str(), buf);
return buf->st_mtim;

至少可以说,这很奇怪。你运气不好,它没有立即崩溃,但没有人真正知道它在哪里写结果;可能会在途中覆盖其他一些重要数据。您应该自己分配buf,并将其地址传递给stat,例如:

struct stat buf = {0};    // or memset(0)
stat(filename.c_str(), &buf);
return buf.st_mtim;

您可能还应该检查stat的错误状态,但如果缓冲区为零,它只会返回0,这可能很好。

相关内容

最新更新