Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
293 views
in Technique[技术] by (71.8m points)

bash - Ctrl-C doesn't always terminate a shell script

I have two scenarios:

#!/usr/bin/env bash
  
sleep infinity
# When I type Ctrl-C here, "sleep" command and script are stopped so I didn't see "End"

echo End
#!/usr/bin/env bash
  
docker exec container-id sleep infinity
# When I type Ctrl-C here, "docker exec" command is stopped but script continued so I saw "End"

echo End

Why the difference in behaviour?

question from:https://stackoverflow.com/questions/65644307/ctrl-c-doesnt-always-terminate-a-shell-script

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

That's how bash behaves when its process group receives a SIGINT but the program currently running on the foreground terminates normally. Take these two for example:

$ bash -c 'sh -c "trap true INT; sleep 10"; echo reached'
^Creached
$
$ bash -c 'sleep 10; echo reached'
^C

echo is reached in the first case because SIGINT is caught and handled by sh (as otherwise it wouldn't be possible to run the trap set for it), and ignored by bash since it didn't interrupt sh when it arrived.

In the second, sleep is interrupted as it doesn't catch SIGINT. Bash discerns this (using WIFSIGNALED and WTERMSIG macros), resets the handler for SIGINT to default, and signals itself to stage a SIGINT-caused termination.

The rationale for this behavior is given here as follows:

The basic idea is that the user intends a keyboard-generated SIGINT to go to the foreground process; that process gets to decide how to handle it; and bash reacts accordingly. If the process dies to due SIGINT, bash acts as if it received the SIGINT; if it does not, bash assumes the process handled it and effectively ignores it.

Consider a process (emacs is the usual example) that uses SIGINT for its own purposes as a normal part of operation. If you run that program in a script, you don't want the shell aborting the script unexpectedly as a result.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...