Today I was investigating a potential implementation for one specific aspect of the application I am working on and that requires me to spawn a process which will create a file and the lifetime of the file needs to be tied to the lifetime of the owning process.
I could easily create the file when the process starts and delete it when the process is about to exit; the problem with this solution is that there are way too many things that can go wrong regarding deleting the file (for instance, if the process is terminated by Process.Kill() it is game over, i.e, it will not have a chance to delete the file).
Luckily there is a better alternative: to create the file with the option FileOptions.DeleteOnClose in which case the OS (Windows) guarantees that the file will be deleted when the last file handle is closed.
That is exactly what I need! The only problem is that the documentation of FileOptions enumeration is not clear about a very important detail: if you want to allow other process to be able to access that file you must specify FileShare.Delete (among other share modes you want to grant), otherwise any attempt to open the file will fail. Luckily the documentation for CreateFileW is more explicit about this:
Subsequent open requests for the file fail, unless the FILE_SHARE_DELETE share mode is specified.
So I was able to figure that out (but not without a good amount of head scratching :( )
Hope this helps.
Adriano
No comments:
Post a Comment