Linux中'Ctrl + c'按键的作用


=Start=

缘由:

「What does CTRL-c do?」

正文:
  • Ctrl-c 是向终端发送 SIGINT 信号「intr = ^C」,终止一个进程/任务
  • Ctrl-z 是向终端发送 SIGSTOP 信号「susp = ^Z」,挂起一个进程/任务(任务并没有结束,它仍然在进程列表中,只是维持挂起的状态(T),用户可以使用fg/bg命令继续前台或后台的任务,fg命令重新启动前台被挂起的任务,bg命令把被挂起的任务放在后台执行)
  • Ctrl-d 不是发送信号,而是表示一个特殊的二进制值「eof = ^D」,表示 EOF ;在Windows下是通过组合键 Ctrl-z 来表示 EOF

Linux、Mac下可以通过 `stty -a` 命令看终端配置(也可以通过`stty`命令进行修改):

#CentOS
$ stty -a
speed 38400 baud; rows 59; columns 270; line = 0;
intr = ^C; quit = ^\; erase = ^?; kill = ^U; eof = ^D; eol = <undef>; eol2 = <undef>; swtch = <undef>; start = ^Q; stop = ^S; susp = ^Z; rprnt = ^R; werase = ^W; lnext = ^V; flush = ^O; min = 1; time = 0;
-parenb -parodd cs8 -hupcl -cstopb cread -clocal -crtscts -cdtrdsr
-ignbrk -brkint -ignpar -parmrk -inpck -istrip -inlcr -igncr icrnl ixon -ixoff -iuclc -ixany -imaxbel -iutf8
opost -olcuc -ocrnl onlcr -onocr -onlret -ofill -ofdel nl0 cr0 tab0 bs0 vt0 ff0
isig icanon iexten echo echoe echok -echonl -noflsh -xcase -tostop -echoprt echoctl echoke

#Mac OSX
$ stty -a
speed 38400 baud; 59 rows; 270 columns;
lflags: icanon isig iexten echo echoe echok echoke -echonl echoctl
-echoprt -altwerase -noflsh -tostop -flusho pendin -nokerninfo
-extproc
iflags: -istrip icrnl -inlcr -igncr ixon -ixoff ixany imaxbel iutf8
-ignbrk brkint -inpck -ignpar -parmrk
oflags: opost onlcr -oxtabs -onocr -onlret
cflags: cread cs8 -parenb -parodd hupcl -clocal -cstopb -crtscts -dsrflow
-dtrflow -mdmbuf
cchars: discard = ^O; dsusp = ^Y; eof = ^D; eol = <undef>;
eol2 = <undef>; erase = ^?; intr = ^C; kill = ^U; lnext = ^V;
min = 1; quit = ^\; reprint = ^R; start = ^Q; status = ^T;
stop = ^S; susp = ^Z; time = 0; werase = ^W;

如果不希望 Ctrl-c 按键起作用,或者想要插入自己的处理程序,可以使用stty禁用该功能,或者使用trap捕获该信号,插入自己的处理程序。

#使用stty禁用该(Ctrl-c)功能

在bash脚本中插入如下命令即可:

stty intr undef

请注意,该命令同时把整个终端的设置都改掉,导致 Ctrl-c 对于其它程序也不能用,所以在你的程序末尾还要将 Ctrl-c 恢复,使用如下命令:

stty intr ^c
#使用trap捕获该(Ctrl-c)信号

首先定义一个处理函数,比如 cleans ,用于捕获信号后的处理。

cleans() {
    echo "user cancelled, exit..."
    exit 1 #如果不希望退出,可以删掉此行
}

然后使用trap捕获信号

trap "{ cleans; }" 1 2 3 6 9 15

花括号中是处理函数的名称,后面的数字是信号量的代号。使用 kill -l 命令可以查看各种信号量的代码,其中中断信号(SIGINT)就是2。

参考链接:

=END=

, ,

《 “Linux中'Ctrl + c'按键的作用” 》 有 2 条评论

回复 a-z 取消回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注