I am monitoring a folder for new files and need to process them. The problem is that occasionally file opening fails, because system has not finished copying it.
Wha
In fact, to avoid race conditions, the only safe solution is to retry.
If you do something like:
while (file is locked)
no-op()
process file()
You risk another process jumping in between the while guard and the process file statement. No matter how your "wait for file availability" is implemented, unless you can ensure that post-unlock you're the first process to access it, you might not be that first user.
This is more likely that might seem at first glance, in particular if multiple people are watching the file, and in particular if they're using something like the file-system watcher. Course, it's still not particularly likely even then...