Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I send a signal from a python program?

I have this code which listens to USR1 signals

import signal import os import time  def receive_signal(signum, stack):     print 'Received:', signum  signal.signal(signal.SIGUSR1, receive_signal) signal.signal(signal.SIGUSR2, receive_signal)  print 'My PID is:', os.getpid()  while True:     print 'Waiting...'     time.sleep(3) 

This works when I send signals with kill -USR1 pid

But how can I send the same signal from within the above python script so that after 10 seconds it automatically sends USR1 and also receives it , without me having to open two terminals to check it?

like image 992
user192082107 Avatar asked Feb 26 '13 02:02

user192082107


People also ask

How do you send a signal from a Python script?

8.1: Send Signal to a Thread and Wait for it using sigwait() It then waits for the list of signals (SIGTERM and SIGALRM) using sigwait() method. Once the signal is received, it retrieves the handler of the signal and executes it. Our main code starts by registering a handler with SIGTERM signal.

How do you catch signals in Python?

Python allows us to set up signal -handlers so when a particular signal arrives to our program we can have a behavior different from the default. For example when you run a program on the terminal and press Ctrl-C the default behavior is to quit the program.

How do you write a signal handler in Python?

You can use the functions in Python's built-in signal module to set up signal handlers in python. Specifically the signal. signal(signalnum, handler) function is used to register the handler function for signal signalnum . Show activity on this post.


1 Answers

You can use os.kill():

os.kill(os.getpid(), signal.SIGUSR1) 

Put this anywhere in your code that you want to send the signal from.

like image 101
moomima Avatar answered Sep 22 '22 06:09

moomima