Catching a SIGINT signal to terminate a custom shell
Here's a trivial implementation of SIGINT
assisted handling sigaction
that will work on posix systems. Exclude error checking for brevity. The related manual should explain sigaction
.
Basically the program loops through an infinite loop and aborts if the user types exit. Using write
as you cannot use printf in a signal handler. See signal manual
for a list of functions that can be safely used in a signal handler.
#include<stdio.h>
#include<signal.h>
#include<string.h>
#include<stdlib.h>
char s[]="Type 'exit' to terminate\n";
void int_handler (int signum)
{
write(fileno(stdin), s, sizeof s - 1);
}
int main (void)
{
char str[256];
struct sigaction sh;
sh.sa_handler = int_handler;
sigemptyset (&sh.sa_mask);
sh.sa_flags = 0;
sigaction (SIGINT, &sh, NULL);
printf("%s", s);
while(1) {
fgets(str, sizeof str, stdin);
char *p = strchr(str, '\n');
if(p) *p = 0;
if(!strcmp(str, "exit")) {
printf("Exiting on request...");
break;
}
}
return 0;
}
source to share
Ctrl + C sends an interrupt (SIGINT) signal to the current process. You can use signal () to catch SIGINT like this:
#include<stdio.h>
#include<signal.h>
void sigint_handler(int sig)
{
printf("Type exit to close the shell!\n");
}
int main()
{
signal(SIGINT, sigint_handler);
/*Your code should replace the while loop.*/
while(1)
{
printf("Running!\n");
getchar();
}
return 0 ;
}
source to share
As you talk about how to do this from the shell, you probably want:
$ trap "echo Please type \'exit\' to close the shell." SIGINT
<Ctrl-C>
Please type 'exit' to close the shell.
$
This specifies the command to execute when capturing the specified signal (the command trap
can also capture other signals, SIGINT is the one that is generated Ctrl-C
). \'
protects the quote from shell interpretation.
source to share