我有一個將結果寫入文件的程序,我希望從該文件實時讀取。這是一個普通的文本文件,外部程序總是寫一整行。我需要在Linux系統上運行它。從正在修改的文件中讀取C
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);
}
這是一個正確的方法嗎?或者,檢查修改時間然後打開文件會更好嗎?如果文件將在同一時間被修改,讀取可能會崩潰嗎?
漂亮的比賽條件蛋糕... – 2012-08-30 23:05:34
爲什麼不使用管道?那麼你不必經歷文件共享,開放和尋求的麻煩。看到這個:http://stackoverflow.com/questions/1072125/how-does-piping-work-in-linux –
外部程序由便攜式批處理系統(PBS隊列)調度。當到達停頓時間(超時)時,PBS是否也會終止管道進程? – Tombart