“拖尾” C/C 中的多个文件++ (Linux)使用inotify(竞争条件?)

发布于 2025-01-05 05:03:38 字数 867 浏览 2 评论 0原文

当使用 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. 轮询返回信号文件已添加到
  2. 我读取直到文件末尾
  3. ,然后文件被添加到
  4. 然后我开始轮询

我会被卡住直到文件再次添加到吗?由于 inotify_add_watch 函数仅接受文件名,因此它不知道我“离开”的位置?

When tailing multiple files in C/C++ using inotify, is there a risk of a race condition when you read to the end of the file, then the file is written to before you start to poll?

The relevant piece of code starts like:

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)) {

Does the poll function only return when the file is modified? So what happens if the following sequence happens:

  1. poll returns signalling file has been added to
  2. I read until the end of the file
  3. then the file gets added to
  4. then I start to poll

will I be stuck until the file is added to once again? Since the inotify_add_watch function only takes file names, it has no idea where I "left" off?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

伏妖词 2025-01-12 05:03:38

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

You must read to the end of file after you create the notification. Otherwise, you have exactly this race condition. When you get a notification, you must re-arm the notification system before you read the file to ensure that you get notified of any change that occurred after you read the file.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文