4

I have a Bash script that launches a Python program. The Bash script handles SIGINT, SIGTERM and SIGHUP signals to do a cleanup operation. I noticed that when I close the process in a tab in LXTerminal, the cleanup process happens. But when I close the entire terminal window, the cleanup process closes.

What am I missing to have the cleanup process to happen?

janos
  • 11,341
  • Have you tried using strace? – Wildcard Oct 08 '15 at 01:32
  • 2
    OP says the script handles SIGHUP; however SIGHUP is what I see when testing this. Lacking a script to demonstrate the problem, there's nothing to test. – Thomas Dickey Oct 16 '16 at 20:21
  • The process is probably "closing" because it gets a I/O error when still trying to read or write to the terminal after receiving the SIGHUP informing it that the terminal has been torn up and is no longer usable. –  Apr 04 '19 at 08:44
  • also see this https://unix.stackexchange.com/questions/491626/why-does-closing-terminal-emulator-window-terminate-a-bash-process-with-sighup-t/491650#comment902939_491650 –  Apr 04 '19 at 08:59

1 Answers1

1

Here's a script that generates a script that will try to catch all signals. The script it generates (sigcatcher.sh) outputs the name of the caught signal before exiting.

#!/bin/sh

# generate a shell function for each and every available signal.

/bin/kill -l | tr ' ' '\n' |
while read signal; do
    cat <<END_OF_FUNCTION
handle_$signal () {
  echo "Caught $signal"
  exit
}

trap 'handle_$signal' $signal

END_OF_FUNCTION
done >sigcatcher.sh

echo 'echo "$$"; sleep 600' >>sigcatcher.sh

On my system (OpenBSD), /bin/kill -l generates a list of available signals on one line, that's why the tr is there to break it up.

The generated script will look something like this:

handle_HUP () {
  echo "Caught HUP"
  exit
}

trap 'handle_HUP' HUP

handle_INT () {
  echo "Caught INT"
  exit
}

trap 'handle_INT' INT

(etc.)

And it will be finished off with

echo "$$"; sleep 600

It outputs its PID and sleeps for 10 minutes.

You run it like this:

$ sh ./sigcatcher.sh >sigcatcher.out

Then you close the window, and then you inspect sigcatcher.out.

I don't run X Windows, but when I kill the tmux pane that this script is running in, I get "Caught HUP" in the output file.

Kusalananda
  • 333,661