tags:

views:

40

answers:

3

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.

A: 

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

pgrep my_process || ./my_process
Benoit
Dolester
+3  A: 

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.

Aaron Digulla
Darron
@Darron: Thanks! For some reason, I'm wary to add anything after the `<<`.
Aaron Digulla
A: 

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
mezzie