gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 08:19:06 25 4
gpt4 key购买 nike

我目前正在尝试使“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,这可能没问题。

关于c - sys 函数调用 "stat"会更改我的文件吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34108534/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com