Capturing SIGSTOP

S

Steven D'Aprano

I'd like to perform a task when the user interrupts my application with
Ctrl-Z on Linux. I tried installing a signal handler:


import signal

def handler(signalnum, stackframe):
print "Received signal %d" % signalnum

signal.signal(signal.SIGSTOP, handler)

But I got a RuntimeError:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
RuntimeError: (22, 'Invalid argument')


This isn't documented:

http://docs.python.org/library/signal.html#signal.signal


Is there a way to catch SIGSTOP?
 
S

Steven D'Aprano

In the strictest sense, no; SIGSTOP can't be caught. However, some
systems have SIGTSTP which is sent when you hit Ctrl-Z, which would be
what you're looking for.

That's exactly what I'm looking for, thanks.

After catching the interrupt and doing whatever I need to do, I want to
allow the process to be stopped as normal. Is this the right way?

import signal, os

def handler(signalnum, stackframe):
print "Received signal %d" % signalnum
os.kill(os.getpid(), signal.SIGSTOP) # Hit myself with a brick.

signal.signal(signal.SIGTSTP, handler)


It seems to work for me (on Linux), but is it the right way?
 
C

Chris Angelico

   os.kill(os.getpid(), signal.SIGSTOP)  # Hit myself with a brick.

Sometimes there'll be a raise() function but it's going to do the same
thing. Yep, that would be the way to do it.

ChrisA
 
C

Chris Angelico

   os.kill(os.getpid(), signal.SIGSTOP)  # Hit myself with a brick.


It seems to work for me (on Linux), but is it the right way?

And - if your system has SIGTSTP, it'll have SIGSTOP and this will be
how it works. (Windows has neither.) This code will probably work fine
on all modern Unix-like systems, but if it fails anywhere, it'll be
for lack of SIGTSTP I would say.

ChrisA
 

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

Forum statistics

Threads
473,995
Messages
2,570,236
Members
46,825
Latest member
VernonQuy6

Latest Threads

Top