gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 09:39:51 24 4
gpt4 key购买 nike

我有一个启动外部程序 (evtest) 两次的 bash 脚本。

#!/bin/bash

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

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

据我所知,evtest 只能通过 Ctrl-C 终止。问题是这也终止了父脚本。这样,对 evtest 的第二次调用将永远不会发生。

如何在不关闭脚本的情况下关闭第一个 evtest,以便第二个 evtest 真正运行?

谢谢!

P.S.: 对于那些想问“为什么不手动运行 evtest 而不是使用脚本?”的人,答案是这个脚本包含进一步的半自动化硬件调试测试,所以它启动脚本并执行所有操作更加方便,无需运行更多命令。

最佳答案

您可以使用trap 命令来“捕获”信号;这是 C 和大多数其他编程语言中用于捕获信号的 signal()sigaction() 调用的 shell 等效项。

陷阱为子 shell 重置,因此 evtest 仍将作用于 ^C 发送的 SIGINT 信号(通常通过退出) ,但父进程(即 shell 脚本)不会。

简单的例子:

#!/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

还有一个变体仍然允许您通过在一秒钟内按 ^C 两次来退出主程序:

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

关于bash - 使用 Ctrl-C 终止程序而不终止父脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36220735/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com