Simply doing process.pid + 1
won't kill that process, it just happened that at that moment your child forked from it's parent, without other process starting.
Your process.pid
is not the actual pid of your image conv1.jpg
.So we need to find it's true pid:
import subprocess
import os
import time
import signal
process = subprocess.Popen(['xdg-open', 'stroke.png'])#I have linux machine and stroke.png is a file which I need to open.
print(process.pid)
time.sleep(5)
print(process.pid)
a = subprocess.Popen(['ps', '-eo', 'pid,ppid,command'], stdout = subprocess.PIPE)
b = subprocess.Popen(['grep', 'stroke.png'], stdin = a.stdout, stdout = subprocess.PIPE)
output, error = b.communicate()
output = output.decode("utf-8").split('\n')
pid = ''
pid = int(pid.join(list(output[0])[1:5]))
print(pid)
os.kill(pid, signal.SIGKILL)
Here what we do is we take two process a
and b
.
a
gives all the pid's, so we need to filter out the pid's for our file in my case stroke.png
in process b
using grep.
We give stdout of a
to stin of b
and then stdout of b to output
.
We need to decode output
to utf-8 because it returns in bytes and we need it in string.
print(output)
Gives us the following result:
[' 7990 1520 eog /home/rahul/stroke.png', ' 8004 7980 grep stroke.png', '']
So we need the number 7990
which is the true pid of our stroke.png
.
This is taken by using int(pid.join(list(output[0])[1:5]))
which gives us the numbers from position 1 to position 4 in our string which is at position 0 in list output
then we join()
them and wrap them in int
because to kill pid we need an integer.
The output my program gives is:
rahul@RNA-HP:~$ python3 so5.py
7982
7982
7990
Here 7982
was the pid of our subprocess and 7990
is the pid of our stroke.png
Hope it helps
Comment if anything can be improved.