通过键盘输入暂停脚本

时间:2018-04-04 09:41:35

标签: bash

(抱歉我的英语不好。)我想通过按[SPACE]栏暂停正在运行的脚本。脚本必须运行,直到用户不按[SPACE]条,然后暂停20秒,然后运行。如何在脚本运行时连续观看键盘输入?

3 个答案:

答案 0 :(得分:3)

一种方法:

#!/bin/bash -eu
script(){ #a mock for your script
    while :; do
        echo working
        sleep 1
    done
}

set -m #use job control
script & #run it in the background in a separate process group
read -sd ' ' #silently read until a space is read
kill -STOP -$! #stop the background process group
sleep 2 #wait 2 seconds (change it to 20 for your case)
kill -CONT -$! #resume the background process group
fg #put it in the forground so it's killable with Ctrl+C

答案 1 :(得分:0)

我建议使用一个控制脚本冻结你繁忙的脚本:

kill -SIGSTOP ${PID}

然后

kill -SIGCONT ${PID}

允许该过程继续。

有关详细说明,请参阅https://superuser.com/questions/485884/can-a-process-be-frozen-temporarily-in-linux

答案 2 :(得分:0)

我认为最简单的方法是使用检查点实现脚本,该检查点测试是否需要暂停。当然,这意味着你的代码永远不会调用'long'运行命令......

更复杂的解决方案是使用SIGPAUSE signal。您可以拥有执行脚本的主进程和捕获[SPACE]并将SIGPAUSE发送到主进程的side进程。在这里,我看到至少两个问题: - 如何在2进程之间共享终端/键盘(如果您的主脚本不希望键盘输入,则简单), - 如果主脚本启动了几个进程,则必须处理进程组...

所以这真的取决于脚本的复杂性。您可以考虑仅依靠Bash提供的常规Job控件。

相关问题