salza
salza

Reputation: 11

Return value of kill?

CHILD=$!                       
sleep 2; 
if  kill -KILL ${CHILD} 2>/dev/null; then
  echo "*** timed out after 2 seconds"
  KILLED=yes
else 
  echo "terminated within time limit"
  killed=no
fi
wait ${CHILD}

I'm a little confused on what is going on here and how the 'if' executes. My understanding is that this checks if killing a child process was successful then setting the KILLED variable to yes and printing out a message. Otherwise set KILLED to no and print a different message.

I thought that when a command is successful it returns a 0? If that's true wouldn't the 'if' interpret that as false and execute the else?

I'm also confused on what the messages printed out mean. I think I'm not understanding the difference between 'timed out' and 'terminated'. (i.e. I would assume the 'terminated' message would go where the 'timed out' message is, and vice versa).

Thanks!

Upvotes: 1

Views: 6334

Answers (2)

pieman72
pieman72

Reputation: 864

It's a little counter-intuitive if you're coming from a language like C or Java, but in bash, a 0 exit status is actually interpreted as true. Here's an excerpt from the manual:

The most compact syntax of the if command is:

if TEST-COMMANDS; then CONSEQUENT-COMMANDS; fi

The TEST-COMMAND list is executed, and if its return status is zero, the CONSEQUENT-COMMANDS list is executed. The return status is the exit status of the last command executed, or zero if no condition tested true.

This is pretty useful, because there are usually a lot of ways a process can fail (giving different non-zero statuses), but only one way for everything to work correctly (zero status).

I think your other questions answer themselves after that :-)

Upvotes: 2

John1024
John1024

Reputation: 113814

kill returns an exit code of 0 (true) if the process still existed it and was killed. In this case, KILLED=yes.

kill returns an exit code of 1 (false) if the kill failed, probably because the process was no longer running. In this case, KILLED=no.

Upvotes: 0

Related Questions