Shayan Peyghambari Shayan Peyghambari - 1 month ago 6
Linux Question

How to see if the process was killed?

When you want to set a time limit for a process, you can simply use

timeout
before the process:

timeout 1.5s COMMAND


This will kill the
COMMAND
if it was not done after 1.5 seconds.

I used that command in some bash scripts; How can i know if one process was completely done before the time limit, or it was killed (because of exceeding the time limit)?

Answer

The Gnu timeout command normally returns a status code of 124 if the timeout was exceeded. Otherwise, it returns the status code returned by the command itself. So you can test the status code by grabbing the value of $? immediately after executing timeout:

timeout 1.5s COMMAND
status=$?
if ((status==124)); then
  # command timed out
elif (status!=0)); then
  # command terminated in time, but it returned an error status
else
  # command terminated in time and reported success
fi

If your command might return the status code 124, then you would have to use the --preserve-status option and check to see if the command was terminated by the signal you tell timeout to send. See the man timeout for details.