1

I have a timer based application that might write a short line to a file every 8 hours. The file doesn't stay open for the 8 hour duration, I just open it, write and close it. If it helps, I open the file for writing only, not appending, so the previous data in it doesn't need to be saved.

What would happen if the user closes the application through task manager while the file is open for writing? Can I make the file writing operation atomic? Or can I at least prevent the application from closing if the file is open?

devil0150
  • 1,350
  • 3
  • 13
  • 36
  • You can do this: 1) create another file, 2) rename this another file into the file you need to overwrite. Rename is atomic operation. – Ilya Jul 26 '16 at 08:56
  • If the process is stopped right before the renaming, wouldn't that leave another unnecessary file in the directory? – devil0150 Jul 26 '16 at 09:08
  • @devil0150 Yes, but if the application is opened again, there could be a check to remove the file on launch. As for leaving an unnecessary file, that is going to happen. – techydesigner Jul 26 '16 at 09:13

1 Answers1

1

What would happen if the user closes the application through task manager while the file is open for writing?

Unless you have an exit handler for the program, the program would most likely close immediately. If the user terminates the program, it would close instantly.

Can I make the file writing operation atomic?

I am unsure what you mean by 'atomic', but here is a link that could help: atomic writing to file with Python

Or can I at least prevent the application from closing if the file is open?

You can't prevent the program from closing if the user terminates the process.

Community
  • 1
  • 1
techydesigner
  • 1,681
  • 2
  • 19
  • 28