我正在将一些 Linux 代码移植到使用lockf()
static string load_bulletin_from_file(const char* cache_filename)
{
int fd = open(cache_filename, O_RDWR); // lockf requires O_RDWR
if (fd == -1) {
etiLog.level(error) << "TAI-UTC bulletin open cache for reading: " <<
strerror(errno);
return "";
}
lseek(fd, 0, SEEK_SET);
vector<char> buf(1024);
vector<char> new_bulletin_data;
ssize_t ret = lockf(fd, F_LOCK, 0);
if (ret == 0) {
// exclusive lock acquired
do {
ret = read(fd, buf.data(), buf.size());
if (ret == -1) {
close(fd);
etiLog.level(error) << "TAI-UTC bulletin read cache: " <<
strerror(errno);
return "";
}
copy(buf.data(), buf.data() + ret, back_inserter(new_bulletin_data));
} while (ret > 0);
close(fd);
return string{new_bulletin_data.data(), new_bulletin_data.size()};
}
else {
etiLog.level(error) <<
"TAI-UTC bulletin acquire cache lock for reading: " <<
strerror(errno);
close(fd);
}
return "";
}
由于lockf()
是 POSIX 函数,Windows 没有它,所以我真的不知道是否有替代品或如何将这段代码移植到 Windows。