Hello All,
I have this script that does stuff like "starting, stopping & restarting" a Daemon Process running on my machine...
My main question is why in part of my code (which you will see below) does the Array Length (i.e. ${#PIDS[@]} )
return "1" when I know the Array is empty..?
Here is a little explaination of the problem...
Occasionally when runnning the "ps auxww" command the output finds more than one instance of the Daemon. Because of
this I save the PID(s) into an array (which is declared at the start of the script), then inside a function I
save the PID(s) into that array. Like this below...
For Example:
### Declare the Array for the PID(s)
declare -a PIDS
:
:
.... Other Code ....
:
:
### START: Function check_ps()...
#####################################
check_ps()
{
### Reset ${PIDS[]} to nothing...
PIDS=""
### Save the Output into an array:
PS_OUTPUT=( $(ps auxww | grep -v grep | grep "/usr/local/bin/Daemon_Process") )
### If this array is NOT empty, then start saving the PIDs
if [ ! -z $PS_OUTPUT ]
then
x=0
for line in "${PS_OUTPUT[@]}"
do
PIDS[$x]=$(echo "$line" | awk -F ' ' {'print $2'})
x=$(($x+1))
done
else
echo "The Daemon is NOT Running!"
fi
}
#####################################
### END: Function check_ps()...
Now if I pass the "stop" argument to the script, after I collect all the PIDs using the code above, I then try to
kill the PIDs. Like this...
stop_daemon()
{
# Call Function check_ps to get the PIDs
check_ps
### If the Array PIDS contains data, then...
if [ ${#PIDS[@]} -gt 0 ]
then
### While The Array still contains data, do...
while [ ${#PIDS[@]} -ne 0 ]
do
### PRINT SOME STUFF FOR TESTING...
echo "LENGTH = ${#PIDS[@]}"
echo -e "ELEMENT 0 = \"${PIDS[0]}\"\n"
kill ${PIDS[0]}
KILL_RETCODE=$?
### Re-Check 'ps auxww' for the daemon
check_ps
done
fi
}
Ok so, I was testing in the while loop in the "stop_daemon()" Function above. Lets say that there was only one PID found.
I had issued some echo commands to see what the values of the variables were since it seemed that it was an endless
loop. I echoed out the Length of the array (i.e. ${#PIDS[@]}) and it ONLY prints "1" everytime, and I also print the
first element of the array (i.e. ${PIDS[0]} ) which prints nothing AFTER the first iteration through the loop.
Example Output:
LENGTH = 1
ELEMENT 0 = "25589"
LENGTH = 1
ELEMENT 0 = ""
LENGTH = 1
ELEMENT 0 = ""
LENGTH = 1
ELEMENT 0 = ""
LENGTH = 1
ELEMENT 0 = ""
^C --> HAVE TO KILL THE SCRIPT TO STOP THE LOOP.
Does anyone know why this loop never terminates? I know some of you will say that I don't need an array since I'm re-checking
the 'ps auxww' output on each loop, but I needed the array in another section of my script. Even still I feel like the loop
should be terminating since it has no elements... I think?
Any thoughts would be great!
Thanks in Advance,
Matt