God_Father
God_Father

Reputation: 601

Kill a background task in mac

I have a task(appium server) running in the background. I started this task by running the command appium & . After running my tests, i need to kill appium. I tried running kill <pid_of_appium> , but the task is not killed immediately. I manually have to press the Enter Key to kill it.

I initially thought this was a problem with appium alone, but I tried running several background tasks and all of these tasks are getting killed only after pressing the Enter key. How can i handle this through code as I need to stop the background task programmatically using a shell command

Upvotes: 0

Views: 842

Answers (3)

nbari
nbari

Reputation: 26915

Give a try to pkill and pgrep:

pgrep, pkill -- find or signal processes by name

To find the process and print the PID you can use:

pgrep -l appium

To kill all the processes you can do:

pkill appium

In case want to send a a KILL 9 signal you could do this;

pkill 9 appium

Upvotes: 0

Jeremy
Jeremy

Reputation: 336

Be careful using kill -9. It can cause corrupted data and potential problems associated with that. I found this script that should attempt to kill the process with a signal -15, and then with a signal -9 as a last resort.

 #!/bin/bash

 # Getting the PID of the process
 PID=`pid_of_appium`

 # Number of seconds to wait before using "kill -9"
 WAIT_SECONDS=10

# Counter to keep count of how many seconds have passed
  count=0

 while kill $PID > /dev/null
   do
# Wait for one second
sleep 1
# Increment the second counter
((count++))

# Has the process been killed? If so, exit the loop.
if ! ps -p $PID > /dev/null ; then
    break
fi

# Have we exceeded $WAIT_SECONDS? If so, kill the process with "kill-9"
# and exit the loop
if [ $count -gt $WAIT_SECONDS ]; then
    kill -9 $PID
    break
fi
done
  echo "Process has been killed after $count seconds."

Upvotes: 1

Charles Srstka
Charles Srstka

Reputation: 17040

If a task doesn't respond to a general kill command, you can try kill -9 instead. Adding the -9 causes the kill program to dispatch a much more ruthless assassin to carry out the deed than the normal version does.

Upvotes: 0

Related Questions