PDA

View Full Version : How to detect a file being successfully created in a folder



bbdaffy
8th November 2010, 05:38
Hi,

Currently my application sends a message to a third party program to ask it to do some sort of image capturing to the file name and path of my choice. However, I am having difficulty trying to determine when the file has been successfully created in my folder. I tried using the QFileSystemWatcher to monitor the folder in which I expect the file to be created. But the notification comes too early, in the sense that the file is still being written to when I try to open it for reading. Any ideas/suggestions how I can detect the file after it has been successfully created? Thanks for your help.

ChrisW67
8th November 2010, 06:04
Can the writer notify you of the completed task through the same channel that your "application sends a message to a third party program" through?

If you are spawning the third-party program as a process that terminates when finished then wait on that event before opening the file. If that program can output to standard output then you can do the whole thing through QProcess.

If you have control of the writer application you can have the writer create two files, file.dat and file.dat.lock, and delete the lock file when finished writing the main file. When the lock file disappears the file is ready. Of course, if you have control of the writer a shared memory segment would be another option.

If you do not have control of the writer you could attempt to open the file for read/write access. If the open fails then back off for a few seconds and try again. Each time it fails wait a little longer (up to some maximum). When the open succeeds the writer's lock on the file has been released. Busy polling is not pretty but if the average processing time is fairly well known then you can tune it it rarely need to retry.

tbscope
8th November 2010, 06:08
In the rare case that the system lets you open a file in read/write mode while the other process is also opening the file in read/write mode, you can try to set a lock yourself. If you can't set a lock, another process has access to the file? Or, this can go wrong and leave your own program with the lock while the other can't write to it?