Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

when terminated the program with Control + c, how to close all open file streams?  RSS feed

 
ahmet oguz
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I write a very simple program that create a dummy log file. I have a BufferedWriter object and writes dummy line to log file. I run this program on linux on command line and when i press the control + c, my open bufferedWriter
stream is not closed. I close the BufferedWriter object on finally block, but if i press the control +c, this block is not run. How do i close this stream also when terminted the program with Control+c
My code=
 
Rob Spoor
Sheriff
Posts: 20893
81
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
System.addShutdownHook should do the trick. From experience, any thread registered using this method will be run even if you interrupt the program (either by pressing CTRL+C or by closing the program from task manager's first tab). The only way they too will be skipped is by really killing the process, from the task manager's second tab (processes).
 
Nitesh Kant
Bartender
Posts: 1638
IntelliJ IDE Java MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ahmet:
How do i close this stream also when terminted the program with Control+c


Apart from academic purpose, I dont think there is any need of doing this.
Whenever a process is terminated/killed(CTRL-C), the file descriptors are released. You really do not need to close the stream in such cases.
 
Maneesh Godbole
Bartender
Posts: 11445
18
Android Eclipse IDE Google Web Toolkit Java Mac Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Rob Prime:
System.addShutdownHook should ...

Runtime#addShutdownHook(Thread hook)
 
Rob Spoor
Sheriff
Posts: 20893
81
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Maneesh Godbole:

Runtime#addShutdownHook(Thread hook)

I stand corrected. I don't use it that often so I had to resort to memory (also being too lazy to open the API ).
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!