1

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)
  • 2
    The documentation says "A negative value -N indicates that the child was terminated by signal N (POSIX only)." What part of that is unclear? – Joseph Sible-Reinstate Monica May 15 at 2:54
  • @JosephSible-ReinstateMonica When I run pkill -9 -f 'java.*7104' in bash shell, the value of $? is 0, why run same command use subprocess.run, the return code is -9? – Ren May 15 at 3:01
  • When your Python script runs, do you have a process running that matches java.*7104? How about when you do it from bash? – Joseph Sible-Reinstate Monica May 15 at 3:05
  • @JosephSible-ReinstateMonica I have update the question – Ren May 15 at 3:26
  • 1
    Post text, not images of text, and especially not animations of text. – Joseph Sible-Reinstate Monica May 15 at 3:27
1

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)
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.