I'd like to block CTRL-C but it doesn't work as expected. I was following the answer described [here] (https://stackoverflow.com/a/37148777/12512199) but without success.
I must be missing something but can't figure out what. It's as if CTRL-C is intercepted but still propagated:
First I ran the following script and hit CTRL-C; the message is displayed but the script exited.
echo "
#!/bin/bash
trap 'echo "Ctrl C happened"' SIGINT
sleep infinity
" > test.sh
chmod x test.sh
./test.sh
Then I checked if it would behave differently in a container as pid 1:
echo "
#!/bin/bash
trap 'echo "Ctrl C happened"' SIGINT
sleep infinity
" > test.sh
chmod x test.sh
docker rm -f conttest
docker container create --name conttest -it --entrypoint="bash" ubuntu:20.04 -x -c /test.sh
docker cp test.sh conttest:/test.sh
docker container start --attach -i conttest
But no, it's the same behavior. I ran those tests on Unbuntu 20.04. Read https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap but still haven't found any clue ... Any idea?
CodePudding user response:
Control C or any other key combination mapped to intr in output of
stty -a
sends SIGINT to all processes in the foreground. Shell
receives it but so does sleep infinity
which dies and shell exits
because it has nothing to do. If you want your script it to run
continuously and do something on SIGINT you have to use an endless
loop:
#!/bin/bash
trap 'echo "Ctrl C happened"' SIGINT
while true
do
sleep infinity
done
If you only want to ignore SIGINT:
#!/bin/bash
trap '' SIGINT
sleep infinity