0

I am trying to kill java process with name "MyClass" using below python script :

import os
os.system("kill $(ps aux | grep 'MyClass' | grep -v 'grep' | awk '{print $2}')")

But this gives me output as below and the process is still running

sh: 1: kill: Usage: kill [-s sigspec | -signum | -sigspec] [pid | job]... or
kill -l [exitstatus]
512

I know that the $ sign is the problem here but do not know how to make this work.

Any help/hint is appreciated. Thanks.

3
  • How about os.system("kill ps aux | grep 'MyClass' | grep -v 'grep' | awk '{print $2}')? Commented May 19, 2017 at 5:56
  • @kuro that gives error. Thanks though. Commented May 21, 2017 at 15:24
  • May be because SO changed the comment. Add '`' before and after the highlighted portion Commented May 21, 2017 at 15:29

2 Answers 2

1
def terminate_java_process(process_name):
    proc = subprocess.Popen(["jps"], stdout=subprocess.PIPE, shell=True)
    (out, err) = proc.communicate()
    processes = {}
    for line in out.split(b"\n"):
        try:
            process_name=str(line, 'utf-8').split(' ')[1]
        except:
            continue
        process_id= str(line, 'utf-8').split(' ')[0]
        processes[process_name] = process_id
    
    os.system("kill -s TERM 82220")
Sign up to request clarification or add additional context in comments.

Comments

0

Here I have another way:

I am fetching all the processes, by looping each one I'm taking the required one and if it is found just kill them.

I am making use of these concept to find out how many processes are running for the same client, for the same category.

# this will fetch the processes in stdout var
processes = Popen(['ps', '-ef'], stdout=PIPE, stderr=PIPE)
stdout, error = processes.communicate()

for line in stdout.splitlines():

    if (line.__contains__("Process_name to check")):

       pid = int(line.split(None, 1)[0])
       os.kill(pid, signal.SIGKILL)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.