How to test if a file is currently being written to

后端 未结 9 1745
野性不改
野性不改 2020-12-18 21:42

I have an application that must check a folder and read any files that are copied into it. How do I test if a file in that folder is currently being written to? I only want

9条回答
  •  猫巷女王i
    2020-12-18 22:31

    The file that is written to will typically have write locks on it so if you try to open it for write, you'll fail; but OTOH you may have a process that opens, writes, and closes the file - then repeats. I think the simplest and safest way would be simply to check for files that were written to recently, but not TOO recent (e.g. not in the last 2 seconds or so)

    [l.e.] Another point to consider is that if you have a process that writes data in chunck (open-write-close), and you get an exclusive lock for the file (to check that the file is no longer used) - than your external process will fail. I think it's far better to check the timestamps, and only get the exclusive lock after you're reasonably sure that the other process finished writing.

提交回复
热议问题