简体   繁体   English

使用Ctrl-C终止程序而不终止父脚本

[英]Terminate program with Ctrl-C without terminating parent script

I have a bash script that starts an external program ( evtest ) twice. 我有一个bash脚本,可以两次启动一个外部程序( evtest )。

#!/bin/bash

echo "Test buttons on keyboard 1"
evtest /dev/input/event1

echo "Test buttons on keyboard 2"
evtest /dev/input/event2

As far as I know, evtest can be terminated only via Ctrl-C. 据我所知, evtest只能通过Ctrl-C终止。 The problem is that this terminates the parent script, too. 问题在于这也会终止父脚本。 That way, the second call to evtest will never happen. 这样,对evtest的第二次调用将永远不会发生。

How can I close the first evtest without closing the script, so that the second evtest will actually run? 如何关闭第一个evtest而不关闭脚本,以便第二个evtest实际运行?

Thanks! 谢谢!

PS: for the one that want to ask "why not running evtest manually instead of using a script?", the answer is that this script contains further semi-automated hardware debug test, so it is more convenient to launch the script and do everything without the need to run further commands. PS:对于一个想问“为什么不手动运行evtest而不使用脚本?”的人,答案是该脚本包含进一步的半自动硬件调试测试,因此启动脚本和执行所有操作更加方便无需运行其他命令。

You can use the trap command to "trap" signals; 您可以使用trap命令来“捕获”信号。 this is the shell equivalent of the signal() or sigaction() call in C and most other programming languages to catch signals. 这等效于C语言和大多数其他编程语言中的signal()sigaction()调用的外壳程序,以捕获信号。

The trap is reset for subshells, so the evtest will still act on the SIGINT signal sent by ^C (usually by quiting), but the parent process (ie the shell script) won't. 陷阱将为子shell重置,因此evtest仍将对^C发送的SIGINT信号(通常通过退出)起作用,但父进程(即shell脚本)则不会。

Simple example: 简单的例子:

#!/bin/sh

# Run a command command on signal 2 (SIGINT, which is what ^C sends)
sigint() {
    echo "Killed subshell!"
}
trap sigint 2

# Or use the no-op command for no output
#trap : 2

echo "Test buttons on keyboard 1"
sleep 500

echo "Test buttons on keyboard 2"
sleep 500

And a variant which still allows you to quit the main program by pressing ^C twice in a second: 还有一个变体,它仍然允许您通过每秒两次按下^C来退出主程序:

last=0
allow_quit() {
    [ $(date +%s) -lt $(( $last + 1 )) ] && exit
    last=$(date +%s)
}
trap allow_quit 2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM