Neste momento tenho o seguinte:
# this function is meant for future script expansions
# its purpose is clear, i.e. to clean up some temp files
# now, it is doing nothing, just a special null command
cleanup_on_signal() { :; }
# define functions to handle signals
# treat them as errors with appropriate messages
# example calls:
# kill -15 this_script_name # POSIX, all shells compatible
# kill -TERM this_script_name # Bash and alike - newer shells
signal_handler_HUP() { cleanup_on_signal; print_error_and_exit "\\ntrap()" "Caught SIGHUP (1).\\n\\tClean-up finished.\\n\\tTerminating. Bye!"; }
signal_handler_INT() { cleanup_on_signal; print_error_and_exit "\\ntrap()" "Caught SIGINT (2).\\n\\tClean-up finished.\\n\\tTerminating. Bye!"; }
signal_handler_QUIT() { cleanup_on_signal; print_error_and_exit "\\ntrap()" "Caught SIGQUIT (3).\\n\\tClean-up finished.\\n\\tTerminating. Bye!"; }
signal_handler_ABRT() { cleanup_on_signal; print_error_and_exit "\\ntrap()" "Caught SIGABRT (6).\\n\\tClean-up finished.\\n\\tTerminating. Bye!"; }
signal_handler_TERM() { cleanup_on_signal; print_error_and_exit "\\ntrap()" "Caught SIGTERM (15).\\n\\tClean-up finished.\\n\\tTerminating. Bye!"; }
# use the above functions as signal handlers;
# note that the SIG* constants are undefined in POSIX,
# and numbers are to be used for the signals instead
trap 'signal_handler_HUP' 1; trap 'signal_handler_INT' 2; trap 'signal_handler_QUIT' 3; trap 'signal_handler_ABRT' 6; trap 'signal_handler_TERM' 15
Eu quero que o script termine ordenadamente no desligamento, o que agora acontece.
Mas abri uma sugestão de um colega para fazer uma pergunta no CTRL+C ao invés de sair do shell.
Não quero desligar a máquina, não faço isso com frequência, de qualquer forma:
Que sinal é enviado para programas/scripts em execução no desligamento?
Durante o desligamento, os processos em execução são instruídos a parar por init (de sendsigs em implementações antigas, de acordo com @JdeBP)/systemd.
Os demais processos, se houver, recebem um SIGTERM. Os que ignoram o SIGTERM ou não terminam a tempo, logo em seguida são enviados um SIGKILL pelo init/systemd.
Essas ações destinam-se a garantir um desligamento estável/limpo (na medida do possível).
Por curiosidade, veja o relato de um
systemd
bug relacionado (antigo):Bug 1352264 - systemd envia imediatamente SIGKILL após SIGTERM durante o desligamento
Também de
shutdown.c
/main():Também do sysvinit 2.94 sources/init.c, aqui está o código em torno de uma rodada SIGTERM. Se algum processo recebeu um SIGTERM, teste cada segundo durante 5 segundos para ver se há algum processo restante. Deixe a espera se em um desses testes nenhum processo for encontrado, ou envie SIGKILL para o(s) processo(s) restante(s) após os 5 segundos.