0

I have a to execute a process that sometimes produces an error. However every time it produces that error, it doesn't exit the process.

aneesh@nb-14:~$ emulator -no-boot-anim -avd Andreud
Emulator ERROR: Unable to load VM from snapshot. The snapshot file was saved for a
different hardware configuration
^Z
aneesh@nb-14:~$ emulator -no-boot-anim -avd Andreud

On success the cursor is at the beginning of the second line above and the emulator error doesn't show up. On failure it shows the error but I am forced to stop it. The commands might seem to show that this question is off-topic.

However my question is how (via a command) to detect this error while this process is still running and if yes kill it.

1 Answer 1

1

Launch the emulator in the background, sending all of its output to a temporary file

emulator -no-boot-anim -avd Andreud &>/tmp/emulator-output &

Then get the PID of the recently launched process, and store it in a variable called EMULATORPID

EMULATORPID=$!

Then, while the emulator is still running, watch the output file for the error, and when it is found, kill the process by PID:

while ps -p$EMULATORPID ; do
   grep "Emulator ERROR" /tmp/emulator-output && kill $EMULATORPID
done

To satisfy the additional requirement of quitting the while loop after five seconds, you could set a counter, increment it each loop, and add a delay of one section to each iteration like so:

  CTR=0
  while ps -p$EMULATORPID &&  [ $CTR -lt 5 ]  ; do
     grep "Emulator ERROR" /tmp/emulator-output && kill $EMULATORPID
     sleep 1s;
     CTR=$[CTR+1] 
  done
5
  • Is it -p$EMULATORPID ; ... or -p $EMULATORPID ; ... . (space in between?)
    – Karthik C
    Jul 2, 2013 at 15:57
  • Currently a process is running I want to kill it and start fresh. I gave the command kill $!. It teaches me this: kill: usage: kill [-s sigspec | -n signum | -sigspec] pid | jobspec ... or kill -l [sigspec] What must I do?
    – Karthik C
    Jul 2, 2013 at 16:10
  • 1
    ps works with or without a space between the -p and the pid. If you run kill $! and you get a usage message, then $! is probably not defined. You can check that by echoing it, like echo $! . $! is only defined within the specific terminal from which you have launched another process, so you must run all of the commands I listed in order, in the same terminal session. Jul 2, 2013 at 18:10
  • Thanks. However I have an additional requirement. Edited the question.
    – Karthik C
    Jul 3, 2013 at 11:22
  • I've edited my answer. Jul 5, 2013 at 18:40

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .