0

I want to run command pkill -9 -f 'java.*7104' in python3 use subprocess.run, but I do not know why returncode=-9, can anyone explain this?

>>> subprocess.run("pkill -9 -f 'java.*7104'", shell=True)
CompletedProcess(args="pkill -9 -f 'java.*7104'", returncode=-9)

When I run the same command in bash shell, the return code is 0:

$ pkill -9 -f 'java.*7104'
$ echo $?
0

Run command in bash shell:

root@w-test01:/home/renyuntao# ps -ef | grep -E 'java.*7104' | grep -v grep
root     127147      1 99 11:37 pts/1    00:00:13 java -Djava.security.egd=file:/dev/./urandom -Xmx10240m -jar ./aichemy.jar --server.port=7104 --spring.profiles.active=test01_use
root@w-test01:/home/renyuntao# pkill -9 -f 'java.*7104'
root@w-test01:/home/renyuntao# echo $?
0

Run command use subprocess.run:

root@w-test01:/home/renyuntao# ps -ef | grep -E 'java.*7104' | grep -v grep
root     128644      1 99 11:38 pts/1    00:00:22 java -Djava.security.egd=file:/dev/./urandom -Xmx10240m -jar ./aichemy.jar --server.port=7104 --spring.profiles.active=test01_use
root@w-test01:/home/renyuntao# python3
Python 3.5.2 (default, Apr 16 2020, 17:47:17) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import subprocess
>>> subprocess.run("pkill -9 -f 'java.*7104'", shell=True)
CompletedProcess(args="pkill -9 -f 'java.*7104'", returncode=-9)

1 Answer 1

0

Joseph Sible-Reinstate Monica answer the question here:

When you use subprocess.run with shell=True, Python starts a shell process that in turn starts your process. This means that it executes sh -c "pkill -9 -f 'java.*7104'". The pkill process only has special protections to avoid matching itself, not to avoid matching its parent process. You need to adjust your regex to not match itself. Putting a ^ before java is probably the easiest way to do that, like this:

subprocess.run("pkill -9 -f '^java.*7104'", shell=True)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .