Search code examples
linuxshellkillkill-process

Kill command does the job but gives error


I'm using shell script to stop a python service and to do that I'm executing the below command.

ps -ef | grep service.py | grep -v grep | awk '{print $2}' | xargs kill -9

After executing I'm getting below error:

kill: sending signal to 487225 failed: Operation not permitted

But, when I check the terminal where the process is running, it terminates.

/home/saakhan/Documents/scripts/cluster-helpers.sh: line 75: 526839 Killed python3 src/service.py

Now, in my shell script I'm checking for the error if any, while stopping the service. So, it calls that error function which displays "Failed to stop the Service" even though the service is stopped successfully.

Do I need to change the command for this ?

Note: I have to use 'kill' only and not 'pkill


Solution

  • As @Bodo pointed out, there was more than one PIDs and only one of them got killed while the other showed error as it wasn't started by the same user.

    I changed the grep command to filter the process started by the same user and then killed it, so it worked.

    Update:

    I used this command to successfully run my code and terminate the app as needed.

    ps -u | grep service.py | grep -v grep | awk '{print $2}' | xargs kill -9