I want to kill a subprocess if the time of executing is too long. I know I have to use os.kill
or os.killpg.
However, the problems comes out when if I am not a root user. For example, in my designed GUI, I want to call subprocess, and os.kill
or os.killpg
to kill the subprocess. But my GUI is owned by apache. So when it comes to the command os.kill, I will get error:
[type:
exceptions.OSError value: [Errno 1] Operation not permitted
And besides, the version of my python is 2.4.3. so terminate()...can't be used.
Could anyone give me some ideas?
Thanks a lot!
PS Related part of my code:
timeout=4
subp = subprocess.Popen('sudo %s'%commandtosend, shell=True,preexec_fn=os.setsid, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
while subp.poll() is None:
time.sleep(0.1)
now = datetime.datetime.now()
if (now - start).seconds > timeout:
os.kill(subp.pid, signal.SIGKILL)
#os.killpg(subp.pid, signal.SIGKILL)
break
Your subprocess is running with superuser privileges (because you're starting it with sudo). To kill it, you need to be superuser.
One option would be to not use os.kill but run 'sudo kill 5858' where 5858 would be the PID of the process spawned by subprocess.Popen.
It's also worth noting that if your program allows the user to control commandtosend you will give the user superuser rights to the entire machine.
Remove sudo
from the subprocess command if it's possible which you should do because you shouldn't run a subprocess in a sudo user from your GUI , it's definitely a security breach:
subprocess.Popen(commandtosend, shell=True,preexec_fn=os
^^
Here don't put sudo
Like this your subprocess will be launch with the www-data user(Apache user), and you can kill it with os.kill(subp.pid, signal.SIGKILL)
.
If it's not possible to remove the sudo
(which is bad) from the subprocess you will have to execute the kill like this :
os.system("sudo kill %s" % (subp.pid, ))
Hope this can help :)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.