gpt4 book ai didi

c++ - "tailing"C/C++ (Linux) 中使用 inotify 的多个文件(竞争条件?)

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

当使用 inotify 在 C/C++ 中拖尾多个文件时,当您读取到文件末尾时是否存在竞争条件的风险,然后在开始轮询之前写入文件?

相关代码的开头如下:

while (true) {
struct pollfd pfd = { fd, POLLIN, 0 };
int ret = poll(&pfd, 1, 30000); // timeout 30s
if (ret > 0) {
size_t len = read(fd, buf, sizeof(buf));

for (size_t e = 0; e < len; ) {
inotify_event *ev = reinterpret_cast<inotify_event*>(&buf[e]);

int i = 0;
while (wds[i] != ev->wd) {
++i;
}

if (ev->mask & IN_MODIFY) {
FILE* f = ff[i];
fseek(f, pos[i], SEEK_SET);

while (fgets(line[i]+offsets[i], MAX_LINE_LENGTH, f)) {

poll函数是不是只有在文件被修改时才返回?那么如果发生以下序列会发生什么:

  1. poll returns signaling file has been added to
  2. 我一直读到文件的结尾
  3. 然后文件被添加到
  4. 然后我开始投票

我会卡住直到再次添加文件吗?由于 inotify_add_watch 函数只接受文件名,它不知道我“离开”的地方?

最佳答案

创建通知后,您必须读到文件末尾。否则,你就会有这种竞争条件。当您收到通知时,您必须在读取文件之前重新启动通知系统,以确保您在读取文件后发生的任何更改都得到通知。

关于c++ - "tailing"C/C++ (Linux) 中使用 inotify 的多个文件(竞争条件?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9270404/

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