c, how do i detect if another process is writing to a file

Go To StackoverFlow.com

2

I do open large files with fopen under c with a kind-of observed folder logic. I'd like to fopen (or at least to fread) the file as soon as it has been copied completely to my observed folder.

How can i detect if another process is writing to a file? Is that possible with standard-c?

Thanks

2012-04-05 19:54
by Jonas Schnelli
This depends on your OS. If you're on a GNU-based system, grab the source for 'fuser', which lists all open files on a system. That'll show you the API calls necessary for what you want. There are also other utilities that can monitor file system operations and run other processes when conditions are met, but again, those are OS-dependent - Marc B 2012-04-05 19:56
something along the lines of http://stackoverflow.com/questions/876473/is-there-a-way-to-check-if-a-file-is-in-us - enthusiasticgeek 2012-04-05 20:15
also look at http://beej.us/guide/bgipc/output/html/multipage/flocking.html look at "inotify - enthusiasticgeek 2012-04-05 20:17
flock() the file in the writing process and unlock it when you're done, then use flock() with F_TEST in the other process to check if it's locke - strkol 2012-04-05 20:47
@strkol With his description it doesn't seem he has control over the writing proces - Pavan Manjunath 2012-04-05 20:49
@Pavan Manjunath, OK then one ugly linux specific solution is to check in /proc if the file is among the open FDs. The other one is to use fanotify (also linux specific) to monitor when the file is being created and closed - strkol 2012-04-05 21:09


3

There's no way to do it with standard C. The best you can do is heuristically notice when file stops changing, e.g. read the last few blocks of the file, sleep n seconds, then read the blocks again and compare against the previous read. You could also try just watching the end of file seek pointer to see when it stops moving, but for large files (size greater than what will fit in a signed long) the POSIX function ftello() is required to do it portably.

2012-04-05 20:14
by Kyle Jones
fseek to the end and compare the file size is what i'm doing now. It looks like that it works for my case. Thank - Jonas Schnelli 2012-04-06 08:36


-1

It's kind of "rude" but you could keep trying to open it in write mode; as long as it's being written to by some other file, the fopen will fail. Something like this:

FILE* f;
while( (f = fopen( fname, "w" )) == NULL ) {
  sleep( 100 );  // we want to be moderately polite by not continually hitting the file
}
2012-04-05 20:30
by Ethan Brown
I dont think this works. fopen does not check whether anybody's already writing into a file AFAIK. Can you link up some documentation regarding this - Pavan Manjunath 2012-04-05 20:39
It turns out you're right...at least I learned something in the process. Thanks for calling me on that, Pavan - Ethan Brown 2012-04-05 21:42
Ads