1

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 
Jolta
  • 2,620
  • 1
  • 29
  • 42
user1334609
  • 381
  • 4
  • 12

1 Answers1

0

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) &
Fabricio
  • 101
  • 1