Laboratory # 9: Signal Handling
Laboratory # 9: Signal Handling
Laboratory # 9: Signal Handling
SIGNAL HANDLING
Top Command: Top command displays processor activity of your Linux box and also
displays tasks managed by kernel in real-time. It'll show processor and memory are being used
and other information like running processes.
Output:
Ps Command: Report a snapshot of the current processes. Now to select a single required
process we use aux along with ps.
ps = process status
aux Command:
a = show processes for all users
u = display the process's user/owner
x = also show processes not attached to a terminal
To Search a Particular Process:
Open Firefox in background. To search its details, type:
Output:
You can see the PID and name of the process encircled in red above. With the grep command
you can filter a process you want. Note that it’s giving you two results. The last one is the id of
the grep itself. Grep returns PID of itself too so ignore that and copy the first one. Which is
3149 here in this case.
Task: Write a program in C with an infinite loop and a custom signal handler to handle at
least kill -15 (SIGTERM) and kill -9 (SIGKILL). Send both these signals (kill -9 and -15)
using your running process’s PID.
Algorithm:
➢
Write an infinite loop in C
➢
Include header file signal.h
➢
Call signal(signal_name, your_custom_signal_Handler) to catch the signal you
will send.
➢
Write your custom signal Handler function below main and write its
prototype before main.
➢
Compile by typing “gcc –o filename filename.c” in shell.
➢
Then execute it by “./filename”
Solution:
Code:
Main program:
Sending Signal:
Run the program in a shell. The infinite loop will start running. Now open another terminal and
search your process by typing the name of executable file you set by gcc command.
You can see an infinite loop going on in the first terminal at the back and the result of search
in the second terminal at front. Now you need the pid 3201 because it is the id of the running
process, ignore the others.
SIGTERM: Use process pid and send signal. Process will catch it. Since the infinite loop
is running the process will ignore the signal as it is busy and it has the option to ignore.
SIGKILL: Now send SIGKILL and kill it. You can see that the process has stopped execution
and has been killed. Also it couldn’t catch the signal SIGKILL.