Kill an OS process from script (perhaps unix specific)

C

chengiz

Hi,
I'm trying to run a process from a python script. I need the exit
status of that process but do not care about its output, so until now
was using os.system(). But it turned out that the process often went
into an infinite loop, so I wrote a SIGALRM handler. Unfortunately the
code I came up with is quite kludgy:

import subprocess
....
try:
p = subprocess.Popen(..., shell = True)
pid = p.pid
os.waitpid(pid...)
...
except ...: # Thrown by alarm signal handler
os.kill(pid + 1) # "Real" pid = shell pid + 1
...

The os.kill is very hacky and unsafe so I was looking for better
ideas. Any help will be greatly appreciated. Thanks!
 
D

Douglas Wells

Hi,
I'm trying to run a process from a python script. I need the exit
status of that process but do not care about its output, so until now
was using os.system(). But it turned out that the process often went
into an infinite loop, so I wrote a SIGALRM handler. Unfortunately the
code I came up with is quite kludgy:

import subprocess
...
try:
p = subprocess.Popen(..., shell = True)
pid = p.pid
os.waitpid(pid...)
...
except ...: # Thrown by alarm signal handler
os.kill(pid + 1) # "Real" pid = shell pid + 1
...

The os.kill is very hacky and unsafe so I was looking for better
ideas. Any help will be greatly appreciated. Thanks!

Assuming that the problem is really an infinite loop (and not just
an arbitrary delay), you could use the simple construct:

import os
code = os.system ("ulimit -t <secs> ; ...")

That's not guaranteed to work on all POSIX systems, but it should
work with at least ash, bash, and ksh. And it would would be
"limit cputime <secs> ; ..." if you somehow got hooked up with a
C shell.

- dmw
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,819
Latest member
masterdaster

Latest Threads

Top