1

I wrote a shell script which runs large simulations and stores things into a temporary file. I used the trap command clean up after receiving a SIGINT. The problem is, the cleanup is not happening. I ran with -x option to debug and the rm command has been executed. Nevertheless, the file still remains.

Code:

exit_prog() {
    rm tmp
    exit 0
}

print_sim_params() {
    echo "$cur_sz"
}

run_sim() {
    cur_sz="$min"
    while [ "$cur_sz" -le "$max" ]; do



        ./sim "$cur_sz"  | awk '{ print $1, " ", $11 >> "tmp" }' &
        wait
        cur_sz=`expr $step + $cur_sz`
    done
    wait
}

trap exit_prog SIGINT
trap print_sim_params SIGUSR1

And here is part of the output when used with -x option, as you can see exit_prog was invoked.

+ run_sim
+ cur_sz=100
+ '[' 100 -le 110 ']'
+ ./sim 100 10000
+ wait
+ awk '{ print $1, " ", $11 >> "tmp" }'
++ expr 1 + 100
+ cur_sz=101
+ '[' 101 -le 110 ']'
+ ./sim 101 10000
+ wait
+ awk '{ print $1, " ", $11 >> "tmp" }'
++ exit_prog
++ rm tmp
++ exit 0
Jolta
  • 2,620
  • 1
  • 29
  • 42
mrQWERTY
  • 4,039
  • 13
  • 43
  • 91

1 Answers1

2

What if you add -f flag to rm call?

exit_prog() {
    rm -f tmp.state
    exit 0
}

Also you can return exit code from rm call to see what happened:

exit_prog() {
    rm -f tmp.state
    exit $?
}
Vladimir Posvistelik
  • 3,843
  • 24
  • 28