handling SIGINT in shell scripts when executing another shell script.

handling SIGINT in shell scripts when executing another shell script.

Post by vikram.she » Sat, 20 Aug 2005 06:57:22


I have a simple shell script foo1.sh that invokes another shell script
foo2.sh, something like below:

#!/bin/sh
SIGINT_handler()
{
echo "## [$DATE_TIME] User interrupt ignored,"
continue
}
trap SIGINT_handler 2

...
./foo2.sh
...

----------
while executing foo1.sh, if the script receives SIGINT, how do I ignore
the SIGINT in foo2.sh ? somehow foo2.sh does not finish to completion
and is killed after receiving SIGINT. but foo1.sh is still executing.
Is there any way to trap this signal in the child script. ? Please
share your thots and inputs on this topic.
Regards,
Vikram Shekhar
 
 
 

handling SIGINT in shell scripts when executing another shell script.

Post by Stephane C » Sat, 20 Aug 2005 07:31:42


[...]

All the processes in the foreground process group of the
terminal will get that message. Oviously a signal handler can't
be inherited accross a execve.

What you can do can be one of:

1:

trap SIGINT_handler INT

(trap '' INT; exec ./foo2.sh)
trap - INT # resume normal SIGINT handling

Here, the shell running foo1.sh will be interrupted and may
run the signal handler. Chances are that it will run it after
foo2.sh is terminated. Many shells will fail badly with that
as the signal handling in shells is something not so well
specified.

2:

trap '' INT
./foo2.sh &
trap SIGINT_handler INT
until wait; do :; done
trap - INT # resume normal SIGINT handling

The SIGINT will only break the "wait" and the signal handler
can be run and the waiting resumed manually (the problem with
the previous solution is that the resuming was possibly not
done).

3:
trap '' INT
(
trap SIGINT_handler INT
. ./foo2.sh
)

Here, foo2.sh is interpreted by a child of the one
interpreting foo1.sh. It's a bit like editing foo2.sh and
adding a line at the top.

But note that whatever command foo2.sh is running at the time
of the SIGINT will be interrupted.

foo2.sh will also inherit the variables and functions of
foo1.sh.

4:
(trap SIGINT_handler INT; while :; do sleep 9999; done) &
pid=$!
trap '' INT
./foo2.sh
trap - INT # resume normal SIGINT handling
kill "$pid"

If the point is just to report and ignore the INT signals you
can simply have a process dedicated for that.

I would go for solution 2 or 4.

--
Stephane