I have a program which I'm writing a script for in /etc/init.d.
Problem is, the program does not deamonize itself. It takes like 5 secs to start it and when it has initialized, it prints a string ("Started OK") to stdout.
I'm looking to create script which starts the process, waits a while for the string to appear and then continue the script, indicating failure or success (the string was found).
Obviously this does not work as I want.
daemon $PROGRAM &
Rather
(./proc > some_output) &
poll_output_for "Started OK" 10 secs or die
I think you might be able to use expect to do something like this: see http://expect.sourceforge.net/ or http://en.wikipedia.org/wiki/Expect. This is in repositories for many distributions, e.g. on Ubuntu you can apt-get install expect.
He's a script to simulate your daemon:
#/usr/bin/env /bin/bash
# daemon.sh
sleep 2
echo Started OK
while :; do sleep 1; echo '.' >> daemon.log; done
... and here's an expect script that waits for the output and then exits:
#!/usr/bin/env /usr/bin/expect
spawn -ignore SIGHUP ./daemon.sh
expect "Started OK"
Expect doesn't return until the "Started OK" notification arrives. When it closes the daemon gets a SIGHUP, but we've ignored that so it carries on running. If you inspect the log file (watch cat daemon.log) the daemon should be churning away.
I don't think it should be too hard to get expect to return an appropriate error code - take a look at the manpage for more information.
If I understand you, there's a program that takes 5 or so seconds to start, but runs in the background. You need to wait for this program to start, and this program will still print out "Started OK".
If this program starts, runs in the background, but is still connected to the console, so it can write to the console, you might be able to do something like this:
$prog | tee $prog_out_file
while true
do
sleep 2
grep -q "Started Ok" $prog_out_file && break
done
# Continue here...
The idea is to keep on looping until you see "Started Ok" printed out in the redirected output.