【发布时间】:2012-08-30 23:01:10
【问题描述】:
我有一个程序正在将结果写入文件,我想从该文件中实时读取。这是一个普通的文本文件,外部程序总是写一整行。我只需要在 Linux 系统上运行它。
int last_read = 0;
int res;
FILE *file;
char *buf;
char *end = buf + MAXLINE - 1;
int c;
int fileSize;
char *dst;
while (external_programme_is_running()) {
file = fopen(logfile, "r"); //without opening and closing it's not working
fseek(file, 0, SEEK_END);
fileSize = ftell(file);
if (fileSize > last_read) {
fseek(file, last_read, SEEK_SET);
while (!feof(file)) {
dst = buf;
while ((c = fgetc(file)) != EOF && c != '\n' && dst < end)
*dst++ = c;
*dst = '\0';
res = ((c == EOF && dst == buf) ? EOF : dst - buf);
if (res != -1) {
last_read = ftell(file);
parse_result(buf)
}
}
}
fclose(file);
}
这是正确的方法吗?或者检查修改时间然后打开文件会更好吗?如果同时修改文件,是否可能导致读取崩溃?
【问题讨论】:
-
漂亮的比赛条件蛋糕...
-
为什么不使用管道?那么您不必经历文件共享、打开和查找的麻烦。看到这个:stackoverflow.com/questions/1072125/…
-
外部程序由便携式批处理系统(PBS 队列)调度。当达到壁时间(超时)时,PBS 是否也会杀死管道进程?