Search code examples
qtfile-ioqfilesystemwatcher

When I get directoryChanged signal from QFileSystemWatecher the file newly added is not completed to read


I want to be notified when a file is added to "/test". So I used QFilesystemWatcher's directoryChanged signal. But when "cp aa.txt /test" I got directoryChanged signal and there when I read aa.txt I had incomplete aa.txt.

In this case how can I know the file is completed to read?

FYI, I can't use fileChanged signal since don't know exact file name.


Solution

  • Unfortunately, there's no way to know this in general, without some cooperation from the process that writes to the file. The writing process would need to lock the file for exclusive access, and the reading process would need to keep trying to open the file for reading until it succeeded - when the writing process has dropped the lock.

    All that the directoryChanged signal tells you is what it says on the box: the directory has changed, or in this case, there's a new entry in the directory. This is completely separate from what's represented by that entry - what the contents of the file are.

    The filesystem watcher is only a half of what's needed here, and this is not an issue with Qt, but with the processes. Remember that you're trying to cooperate with the writer.

    As a workaround, if you have some way of validating the file contents, you can do the same while reading and validating the file: keep retrying the read, with some delay until the validation succeeds. To avoid runaway resource use, it may be worthwhile for the delays to form an exponential back-off.