Usage of signal()
- For the signal with a number signum, the signal() system function installs a new signal handler. The signal handler is set to sighandler, which can be either SIG_IGN or SIG_DFL or a user-specified function.
- The following occurs when a signal with the number signum arrives. The signal is disregarded if the relevant handler is set to SIG_IGN. The signal’s default action takes place if the handler is set to SIG_DFL. Finally, if the handler is a function called sighandler, sighandler is executed after the handler has been reset to SIG_DFL or the signal has been blocked, depending on the implementation.
- “Catching the signal” refers to using a signal handler function for a signal. SIGKILL and SIGSTOP signals cannot be intercepted or disregarded.
- The signal() function either returns SIG ERR on failure or the previous value of the signal handler.
Example 1: Illustrating the hangup of the signal using the below command
Syntax:
kill -signal pid
Script:
#!/bin/bash kill -1 500
Output:
Explanation:
The signal is the name or number of the signal that has to be given in the kill command syntax above, and pid is the ID of the process to which the signal needs to be sent. The program executing with the 500 process ID receives the signal called hang-up, or HUP, from the aforementioned command. If no such process is running with pid 500 then a message will be displayed as shown in the above output.
Example 2: Illustrating the killing of signal using the below command
Script:
#!/bin/bash kill -9 500
Output:
Explanation:
Use the above command to send the kill signal to a similar process. The process running under process ID 500 will be terminated by the command already mentioned. If no such process is running with pid 500 then a message will be displayed as shown in the above output.
Signal Handling In Linux Through The signal() Function
A signal is a message or notification issued to your program by the operating system or another application (or one of its threads). Each signal is assigned a number between 1 and 31. Signals are devoid of argument, and most of the time, their names are self-explanatory. For instance, signal number 9 or SIGKILL notifies the program that it is being attempted to be killed.
Contact Us