Reputation: 359
I've written a C program that polls a directory for a file, but I sometimes get an error when trying to access the file. I was wondering whether I need to wait for it to finish being copied or something before trying to use it? I set up a loop to keep loading the image file until the function no longer returned null:
while ( (image = SDL_LoadBMP(path)) == NULL )
printf("image = NULL\n");
and eventually it was no longer null. What is the correct way to handle this?
Upvotes: 1
Views: 581
Reputation: 44240
The best way to handle this is to keep te file in an "invisible" directory while it is being created. And move it to the spool directory once it is closed. (rename() is atomic).
This of course assumes some cooperation from the process that actually produces the files.
BTW: I am assuming UNIX here. Maybe on other platforms similar methods can be used. (changing visibility / readability file attributes, instead of renaming / moving)
Upvotes: 5
Reputation: 3733
It's actually quite hard to do it, especially so to do it reliably. More or less impossible to do so efficiently.
The simplest way to solve the problem is to run fuser
from your C program to determine if some process has the file open.
Lastly, note that if you have a loop waiting for something, it should wait in between retries in order to avoid wasting compute resources. After all, just imagine what computers would be like if every program, on the system did a busy-loop.
EDIT: if you control the application producing the files, the solution suggested by wildplasser@ is best.
Upvotes: 2