If you have developed a shell for your own command line program in python; you are likely to have used something like following code.
try:
# your stuff..
except KeyboardInterrupt:
pass
The above code is used to ignore the KeyboardInterrupt
ie. when you
press Ctrl+c
from the keyboard. python makes it really easy for you.
If you want to do the same thing in c
you need to handle what in nix
world
called as singnals
. Here is a good description of what signals are, it is
taken from yolinux
Signals are software interrupts delivered to a process by the operating system.
Signals can also be issued by the operating system based on system or error
conditions.
What happens when you press Ctrl+c
from the keyboard is the os delivers a
Interrupt signal to the process that is running in your bash or whatever shell
you are currently running. While developing a shell you need to ignore this
interrupt. If you happen to be developing this shell in c
, you will have to
do the following things in order to handle SIGINT
.
- include
signal.h
- Write a function to handle signal.
- Register that function as a callback function for signal.
Following is the demo for that.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
// The callback function.
void
exit_func(int signal_number)
{
if (signal_number == 2)
{
printf("Ctrl+c Pressed, exitting...\n");
}
}
int main()
{
// register the callback function for signal from os.
signal(SIGINT, exit_func);
// do your stuff here
// ...
while (1)
{
sleep(1);
}
return EXIT_SUCCESS;
}