I am writing some C code to process some data in a file, but I just learned that the file is going to be constantly added to (about 1 time/second, maybe faster). So I'm wondering how do I keep reading from the file as its being added to. Then when I get to the end, wait until the next line is added and then process it. Then wait again and then process, and so on and so on. I have something like:
while(1){
fgets(line, sizeof(line), file);
while(line == NULL){
//wait ? then try to read again?
}
//tokenize line and do my stuff here
}
I thought I could maybe use inotify, but I am getting nowhere with that. Does anyone have any advice?
Using
select
can be a good choice but if you do not wish to use it, you can add a sleep for a small amount of milliseconds before reading value.The most efficient way is using inotify, and the direct way is using the
read()
system call directly.using
inotify
The following code may give you some help, It works well on Debian 7.0, GCC 4.7:
When runing the above program. You could test it by create a file or directoy named
/tmp/test_inotify
.A detailed explanation could be found here
Use
read
system callIf a file is open, and have read to the end of current file size. the
read()
system call will return0
. And if some writer wroteN
bytes to this file later, and then theread()
will just returnmin(N, buffersize)
.So it works correctly for your circumstance. Following is an examples of the code.
Reference
You can use
select()
with thefileno(file)
as the file-descriptor.select
will return either with a timeout (if you set a timeout) or when you can read from the file.