[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: [Question] Reliable way to clean up a directory in EXIT trap
From: |
Masahiro Yamada |
Subject: |
Re: [Question] Reliable way to clean up a directory in EXIT trap |
Date: |
Wed, 20 Jul 2022 13:19:33 +0900 |
On Wed, Jul 20, 2022 at 7:27 AM Koichi Murase <myoga.murase@gmail.com> wrote:
> > Why does "trap trapint INT" make the difference?
>
> With an INT trap, Bash will not exit by the INT signal unless the user
> explicitly runs exit or kill. Without the INT trap, Bash might exit at
> the point the user doesn't expect. I've checked the behavior for the
> present case again. You are interrupting the EXIT trap (i.e., "rm -rf
> tmp") by sending INT, but the EXIT trap will not be called again when
> it is interrupted by INT.
Ah, thanks.
I think I almost understood what is happening here.
I modified the test code like follows:
for i in {0..999}; do
(
tmp=$BASHPID.tmp
cleanup() { rm -rf "$tmp"; }
trapint() { cleanup; trap - INT; kill -INT "$BASHPID"; }
trap cleanup EXIT
trap trapint INT
dd if=/dev/zero of="$tmp" bs=1 count=16 2>/dev/null
trap 'echo ouch' INT
)
done
- I used 'dd' because '>> $tmp' is too quick
- I added 'echo ouch' INT trap at the end
If 'ouch' is not shown on interrupt, no tmp file is left-over.
If 'ouch' is shown on interrupt, a tmp file may be left-over.
If Bash receives SIGINT while executing the EXIT trap,
it will run the command 'echo ouch', but never return
to the point where it was interrupted.
This is different from how interrupt handlers are processed.
I think Bash can improve this point:
The EXIT handler should not be interrupted by any signal.
--
Best Regards
Masahiro Yamada