2

I'm writing a script that tries to kill a process. But the process might already been killed by others. How can I guard against it and prevent this kill command from terminating my process with throwing an error? I have PID of the process

Mohsen
  • 2,585
  • How are you selecting the process you want to kill? – Joseph R. Jun 10 '14 at 17:55
  • @JosephR. I have it in a variable inside my bash function – Mohsen Jun 10 '14 at 17:56
  • I meant are you killing the process by name or by PID? – Joseph R. Jun 10 '14 at 17:56
  • @JosephR. PID __ – Mohsen Jun 10 '14 at 17:57
  • Its logical to check the PID first if it exists then KILL it if it does. – Tasos Jun 10 '14 at 18:04
  • 1
    If the PID does not exist because the process has already completed, the kill command will be completely harmless. Why do you even need to check this? – jw013 Jun 10 '14 at 18:22
  • @jw013 I'm guessing this is to avoid failure when running with -e. – Joseph R. Jun 10 '14 at 18:25
  • 2
    @JosephR. The right solution to that (completely different problem) is something along the lines of kill pid || true. When all you have is a PID, it is impossible to avoid race conditions if the state of the PID changes between when you check it and when you try to do something with it. – jw013 Jun 10 '14 at 18:26
  • @Mohsen, I'd be interested in seeing your script. By default, shell scripts will not terminate when a command fails. If your script is failing, preventing it from failing when killing an already dead process should be a matter of just not making the script terminate on error. – ctt Jun 12 '14 at 01:24
  • @ctt It's a Jenkins job. They kill the job if they if a command exit with 0 – Mohsen Jun 12 '14 at 03:19
  • Your best bet, then would be to place your commands in a shell script which runs kill on the PIDs and then exit 0s unconditionally. – ctt Jun 12 '14 at 11:27

1 Answers1

0

Look into using pkill instead of kill. It will return 1 if no process matched. Test exit status of pkill to determine if it actually killed anything