I have found many ways to keep a process running in the background after a bash terminal is closed. However, how can I do the opposite? How can I kill a background process when my terminal is closed?
Currently, when I close the terminal, I get "Processes are running in session... Close anyway?" and if I hit OK, the terminal closes, but the processes are not killed and linger around. Can I hook the suppression of these processes with the "death" of the terminal process?
Easy example: run ssh-agent bash
and then try to close the terminal.
Put this in your .bashrc
:
trap 'kill $(ps -o pid= --ppid $$) 2>/dev/null' exit
This command will make the shell kill all its child processes when you exit.
The trap
command catches signals and other events and lets you execute commands, that run when the signal is catched or the event has happened.
trap [-lp] [[arg] signal_spec ...]
ARG is a command to be read and executed when the shell receives the signal(s) SIGNAL_SPEC. If a SIGNAL_SPEC is EXIT, ARG is executed on exit from the shell.
The kill
command sends a signal to the job(s) of PID(s) supplied as arguments.
kill [-s sigspec | -n signum | -sigspec] pid ...
If neither SIGSPEC nor SIGNUM is present, then SIGTERM (termination signal) is assumed.
The ps
command displays information about processes.
-o format
User defined format of output.
--ppid pidlist
Select which processes to show by PID of their parent process. Selects processes
that are children of those listed in PIDLIST.
Finally, $$
in shell expands to the process id of the shell. In a $(...)
subshell, it expands to the process ID of the current shell, not the subshell.
And 2>/dev/null
is used to discard potential error output of the kill command which can be caused by processes that no longer exist when the kill command is executed, but existed while the ps command was executed - which is typically the subshell $(...)
.