有没有办法可以编写一个简单的脚本来运行程序,大约5秒后关闭该程序,然后重复?
我只是希望能够运行我一遍又一遍地编写的程序,但是这样做我必须在运行它后5秒钟关闭它。
谢谢!
答案 0 :(得分:1)
使用控制操作符&
在后台中启动您的程序,通过$!
可以访问其PID(进程ID),通过该操作可以终止运行睡眠5秒后的程序实例:
#!/bin/bash
# Start an infinite loop.
# Use ^C to abort.
while :; do
# Launch the program in the background.
/path/to/your/program &
# Wait 5 seconds, then kill the program (if still alive).
sleep 5 && { kill $! && wait $!; } 2>/dev/null
done
如果您的命令必须在前台运行以允许用户交互,则需要做更多工作:然后它是在必须在后台运行5秒后终止程序的命令:
#!/bin/bash
# Turn on job control, so we can bring a background job back to the
# foreground with `fg`.
set -m
# Start an infinite loop.
# CAVEAT: The only way to exit this loop is to kill the current shell.
# Setting up an INT (^C) trap doesn't help.
while :; do
# Launch program in background *initially*, so we can reliably
# determine its PID.
# Note: The command line being set to the bakground is invariably printed
# to stderr. I don't know how to suppress it (the usual tricks
# involving subshells and group commands do not work).
/path/to/your/program &
pid=$! # Save the PID of the background job.
# Launch the kill-after-5-seconds command in the background.
# Note: A status message is invariably printed to stderr when the
# command is killed. I don't know how to suppress it (the usual tricks
# involving subshells and group commands do not work).
{ (sleep 5 && kill $pid &) } 2>/dev/null
# Bring the program back to the foreground, where you can interact with it.
# Execution blocks until the program terminates - whether by itself or
# by the background kill command.
fg
done
答案 1 :(得分:0)
查看watch命令。它将让您重复监视输出运行程序。如果你需要在5秒后手动杀死该程序,可能需要有点花哨。
https://linux.die.net/man/1/watch
一个简单的例子:
watch -n 5 foo.sh
答案 2 :(得分:0)
直接回答你的问题:
在睡眠中运行10次5:
#!/bin/bash
COUNTER=0
while [ $COUNTER -lt 10 ]; do
# your script
sleep 5
let COUNTER=COUNTER+1
done
持续跑步:
#!/bin/bash
while [ 1 ]; do
# your script
sleep 5
done
答案 3 :(得分:0)
如果代码上没有输入,您只需执行
即可#!/bin/bash
while [ 1 ]
do
./exec_name
if [ $? == 0 ]
then
sleep 5
fi
done