Keeping a bash script running along the program it has started, and sending the program input

↘锁芯ラ 提交于 2019-12-12 21:15:40

问题


I'm writing a very simple script to control a process, script checks if the process is running, if not: executes it.

I need to expand this with the ability to kill a specific process instance (very one one script has started) after a specified amount of time. Problem is, once bash script is executed it isn't running until the executed program finishes.Ability to pass some input to the process would also be useful, as I have a graceful exit function built in to the service I'm running.

Basically, my bash script should run along the process it's started, and send a kill command via stdin after sleep x times out.

How do I forward some scripted input to the process script has started, and how do I keep the script running after executing the process?

Thanks in advance.


回答1:


If you want to run the process alongside the script, you need to run it in the background:

command &
pid=$!

Now pid will contain the PID of the process you just started. Next you need a way to communicate with the process. If you just need to send some input to the process, use a "here document":

command <<EOF
input
more input
even more input
var=$HOME
EOF

That gets more tricky if you still need to run the process in the background. Either write the input to a temporary file (see mktemp(1)):

tmp=$(mktemp)
cat > "$tmp" <<EOF
input
more input
even more input
var=$HOME
EOF
command < "$tmp" &
pid=$!

or you can use named pipes (FIFOs). This article should get you started.




回答2:


Use pgrep (see man pgrep to see what it does)

pgrep my_process || ./my_process



回答3:


you can easily modify this script to your need but here is a script that will wait for a process to finish or send an email after it has sleep a limited number of time.

#!/bin/sh
SLEEPTIMEOUT=3600
SLEEPCOUNTER=0
SLEEPLIMIT=5

while ps ax | grep -v grep | grep "yourprocess" > /dev/null
do
sleep $SLEEPTIMEOUT
SLEEPCOUNTER=$((SLEEPCOUNTER+1))
echo $SLEEPCOUNTER
if [ $SLEEPCOUNTER -gt $SLEEPLIMIT ]
then
`echo "slept $SLEEPLIMIT times and waited $SLEEPTIMEOUT seconds each time but process is still running" | mailx -s "waited" $EMAIL`
exit 1
fi
done


来源:https://stackoverflow.com/questions/3883051/keeping-a-bash-script-running-along-the-program-it-has-started-and-sending-the

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!