You are not logged in.

#1 2019-06-05 11:40:05

kokoko3k
Member
Registered: 2008-11-14
Posts: 2,481

[SOLVED] Unable to catch/trap TERM signal in bash

Hi all,
sorry for the noobish question, but i'm unable to do this simple task.
I want a bash script to exit "cleanly" when it is terminated.
With the following "script.sh":

#!/bin/bash
trap "echo finish" INT TERM 
sleep 999d

... i'm able to catch CTRL-C from within the same terminal it is started, but i'm unable to catch it from the outside.
If i do killall -TERM script.sh, nothing happens and "finish" is not printed on the terminal.

What am i missing?
Thanks!

--EDIT--
Ok, i found what i was missing, AFAIU sleep is not interruptable because it is not a builtin, so i did something like that:

#!/bin/bash
list_descendants() {
    local children=$(ps -o pid= --ppid "$1")
    for pid in $children ; do
        list_descendants "$pid"
    done
    echo "$children"
}   

finish() {
  echo ; echo TRAP: finish.
  kill $(list_descendants $$)
  exit
}


trap finish INT TERM 
execute_long_processes_in_background &
while true ; do
  sleep 1
done

...wonder if there is a simpler way (?)

Last edited by kokoko3k (2019-06-05 19:12:45)


Help me to improve ssh-rdp !
Retroarch User? Try my koko-aio shader !

Offline

#2 2019-06-05 11:53:00

seth
Member
From: Won't reply 2 private help req
Registered: 2012-09-03
Posts: 78,500

Re: [SOLVED] Unable to catch/trap TERM signal in bash

The active process is sleep and the script doesn't continue. Try to loop "sleep 1", you'll be able to handle the signal every second.

Offline

#3 2019-06-05 11:56:29

kokoko3k
Member
Registered: 2008-11-14
Posts: 2,481

Re: [SOLVED] Unable to catch/trap TERM signal in bash

Thanks, seth, i edited my post while you were answering.


Help me to improve ssh-rdp !
Retroarch User? Try my koko-aio shader !

Offline

#4 2019-06-05 12:13:23

seth
Member
From: Won't reply 2 private help req
Registered: 2012-09-03
Posts: 78,500

Re: [SOLVED] Unable to catch/trap TERM signal in bash

man wait

Offline

Board footer

Powered by FluxBB