Home > Blockchain >  pkill given process depending on input arguments
pkill given process depending on input arguments

Time:12-06

I have a python process running, called test.py that I run from a bash script with input parameters.

$PWD/test.py -s $symbol -folder $folder -n $name -d $name

Once running ps -elf | grep test.py, the process appears with the parameters.

I am trying, within that same bash script, to kill this process given the input arguments:

pkill -f 'test.py -s $symbol -folder $folder -n $name -d $name'

But this doesn't seem to work.

What is the correct syntax? Do I need to add parentheses () or brackets {} somewhere?

CodePudding user response:

As @Aserre mentioned in the comments, you'll need to use double quotes instead of single quotes in your pkill command so that the value of the shell variables is replaced in the string.

Also, take into account that pkill sends SIGTERM by default. Therefore, test.py should have a signal handler to shutdown when it receives SIGTERM. If test.py doesn't have a signal handler, it will ignore the signal and continue to live. If that is the case, use pkill -9, which will kill ptest.py since signal 9 can't be ignored:

pkill -9 -f "test.py -s $symbol -folder $folder -n $name -d $name"

Finally, I'm assuming that test.py runs as a daemon or somehow runs in the background. Otherwise, your bash script will wait until it exits before it continues. If test.py is not a daemon, your bash script can run it in the background. Here is an example:

#!/usr/bin/env bash

symbol=pi
folder=/tmp
name=john
$PWD/test.py -s $symbol -folder $folder -n $name -d $name &
pid=$!
echo "killer: started test.py ($pid)..."

sleep 5
echo "killer: killing test.py..."

# you may use -9 instead of -SIGTERM
pkill -SIGTERM -f "test.py -s $symbol -folder $folder -n $name -d $name"
wait $pid
echo "killer: test.py is dead; exiting..."
  • Related