1

Any idea on how to capture closing the terminal window that my program is running in? While I'm at it, any way to capture when the computer is shutting down but the program is still running, or if the user logs off?

user657178
  • 213
  • 1
  • 3
  • 7
  • What if the power is cut off immediately? Is it necessary to clean up immediately, or would it be possible to clean up at the next start of the program? – Roland Illig Jun 01 '11 at 21:40
  • @Neil: Linux, @Roland power cut-off can be seen as an exceptional case so I'm not handling that – user657178 Jun 02 '11 at 13:16

4 Answers4

2

Try catching SIGTERM. Note that you can not capture SIGKILL which might be what happens during shutdown after a certain amount of time. I found this really nice post that explains some differences too.

[update] Longshot here but what about testing if std-in/out is still open and good? When the terminal dies those file descriptors should be scrapped. Disclaimer, this is a guess at best.

Andrew White
  • 52,720
  • 19
  • 113
  • 137
  • Like I said, I tried testing capturing all the various signals. SIGTERM I geuss will work for Shutdown, haven't tested yet, but it definately does not work for closing terminal... any ideas? – user657178 Jun 02 '11 at 13:17
  • Maybe your program isn't actually being killed when the console does. You should be able to verify that, but either way try testing stdin/stdout to see if they are still "live". That's the best I got. – Andrew White Jun 05 '11 at 23:07
2

If on Unix/Linux: Did you have a look at SIGTERM? This is at least the one sent to you during shutdown.

BjoernD
  • 4,720
  • 27
  • 32
  • SIGTERM will probably work for shut-down, I haven't tested... but it most definately does not work for closing a terminal, which to me is more important right now... any ideas? – user657178 Jun 02 '11 at 13:18
2

You could try the atexit() function ? (see comments)

Or look at this post here: Signals received by bash when terminal is closed

Community
  • 1
  • 1
Gui13
  • 12,993
  • 17
  • 57
  • 104
  • 1
    atexit is only for normal program termination which is defined as "either by a call to exit() or a return from main()" – Andrew White Jun 01 '11 at 21:42
1

From my tests... the signal that my program is receiving when closing terminal is 1 or SIGHUP

user657178
  • 213
  • 1
  • 3
  • 7