Reputation: 3433
Let's say I have this script:
start daemon1 &
start daemon2 &
echo "Running..."
daemon2
can only be started if daemon1
was started successfully.
if daemon1
did not start successfully, then the script most be aborted
"Running..."
should be displayed only if daemon2
started successfully.
if daemon2
did not start successfully, then the script most be aborted
How can I make this with a shell script ?
Upvotes: 0
Views: 1297
Reputation: 4453
I propose you capture the daemon's pid (process id) and then determine if the pid exists (after some delay in case daemon1 takes a while to process to start and crash). So here is a way of achieving that (in Linux, I'm ignoring the 'start' in your commands since I'm not familiar with the windows cmdline environment ):
start daemon1 &
pid1=$!
sleep 3 # give daemon1 some time to get going
if
kill -0 $pid1 2>/dev/null
then
start daemon2 &
pid2=$!
sleep 3 # give daemon2 some time to get going
if
kill -0 $pid2 2>/dev/null
then
echo "Running..."
fi
fi
The necessary ingredients for this recipe are:
$!
returns the child's pid (of the last background process run)
kill -0 <pid>
is a way of determining if a pid is valid (in the process table)
Upvotes: 1
Reputation: 1558
You can check the PID of the started process to see if it is running
start daemon1 &
P=$!
if kill -0 $P > /dev/null 2>&1 ; then
start daemon2 &
P=$!
if kill -0 $P > /dev/null 2>&1 ; then
echo "Running..."
fi
fi
Untested code. Comment if something is not right
Upvotes: 2