In this Python Signals tutorial, we will discuss how to trigger signals through our code using the alarm function. Normally, we can only trigger signals through manual action, such as pressing a specific key combination, or some other special circumstances such as a segmentation fault or illegal instruction.
The Alarm function allows us to trigger any Signal after a given period of time. Let us explore some code now!
The alarm() function takes a single parameter, an integer “n” which specifies the duration after which SIGALRM should be triggered. Before we actually call this function, we will create a custom signal handler for it, so that we can verify that SIGALRM was actually triggered.
import signal
import time
def signal_handler(signum, frame):
print('Alarm Generated @', time.ctime())
signal.signal(signal.SIGALRM, signal_handler)
signal.alarm(5)
time.sleep(10)
You might be wondering why we included a sleep() function call at the end. This is to stop our program from finishing itself before SIGALRM has a chance to execute.
If you want a continuous cycle of SIGALRMs, then you can just make another call to the alarm()
function inside the signal_handler
function. However, you can only one schedule one SIGALRM at a time, so be careful with that.
signal.alarm(0)
If you want to cancel the currently scheduled alarm, then pass in zero into the alarm()
function as shown above.
Note: Is this code not working for you? Are you getting an “signal has no attribute SIGALRM error? That’s because Windows does not support this signal. It is only available on Unix systems (like Linux).
This marks the end of the Trigger Python Signals using alarm() Tutorial. Any suggestions or contributions for CodersLegacy are more than welcome. Questions regarding the tutorial content can be asked in the comments section below.