“拖尾” C/C 中的多个文件++ (Linux)使用inotify(竞争条件?)
当使用 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 函数是否只在文件被修改时返回?那么,如果发生以下序列,会发生什么情况:
- 轮询返回信号文件已添加到
- 我读取直到文件末尾
- ,然后文件被添加到
- 然后我开始轮询
我会被卡住直到文件再次添加到吗?由于 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:
- poll returns signalling file has been added to
- I read until the end of the file
- then the file gets added to
- 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
创建通知后,您必须读到文件末尾。否则,你就会遇到这种竞争条件。当您收到通知时,您必须在读取文件之前重新启动通知系统,以确保您收到读取文件后发生的任何更改的通知。
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.