Why doesn't script call the cleanup and kill the script after 5s, and I also want to get where it stoppped

93 Views Asked by At

The script is designed to kill itself after 5s. But it doesn't kill the script after 5s, and does not call the cleanup. The important thing is that I want to get the value of i when it stopped.

#!/bin/sh
trap "cleanup" TERM 
#call the cleanup when recive TERM
mainpid=$$
#script's pid 
cleanup()
{
    echo "cleaup called"
    echo "i=$i when it is stopped "
    exit 1
}


(sleep 5 && echo "timeout";kill -TERM $mainpid) & 
#after 5s it should kill the script 
run_test()
{
 i=1
sleep 100
i=$$(i+1)


}

run_test 2>&1 > x.log 
1

There are 1 best solutions below

0
On

Because parent processes is waiting for sleep 100 ends the "processing". If you want to process ends before sleep ends, you should kill him too.

something like

(sleep 5 && echo "timeout";kill -TERM `ps -ef | grep $mainpid | grep sleep |  grep -v grep| awk '{print $2}'` $mainpid) &