Catching SIGINT signal to terminate a custom shell - c

Hope you can help me to resolve this problem.
For school I have to transform Ctrl+C to a command which doesn't shut down the shell, but he reminds through printf() that I must type exit to close the shell. I don't even know where to start.
Thank a lot.

Here's a trivial implementation of handling SIGINT using sigaction which will work on posix systems. Left out error checking for brevity. The linked manual should explain about sigaction.
Basically the program loops through an infinite loop and break if user types exit. Using write as you can't use printf in signal handler. See signal manual for a list of functions that can be used safely 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;
}

As you're talking about doing it 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 a command to execute when the listed signal is trapped (the trap command can also trap other signals; SIGINT is the one generated by Ctrl-C). The \' protects the quote from being interpreted by the shell.

Ctrl+C sends an interrupt signal (SIGINT) to the running 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 ;
}

Related

How to handle Control-C signal while designing a shell?

I am trying to implement some of the features present in the shell including quitting only when a user enters quit and not on Ctrl+C. Below is a simplified version of the code that I am tried.
Code 1: without calling loop() in a signal handler.
void loop(){
while(1){
char a[20];
printf("Enter Command : " );
scanf("%s",a);
printf("%s\n", a);
}
}
void sigintHandler(int sig_num)
{
signal(SIGINT, sigintHandler);
printf("\n");
}
int main(int argc, char const *argv[]) {
signal(SIGINT, sigintHandler);
loop();
return 0;
}
The output of Code 1:
As can be seen on a third input, I go to a new line and continued right from where I left the loop. I want to instead start the loop again. So, I did the following modification by calling loop in signal handler itself.
void loop(){
while(1){
char a[20];
printf("Enter Command : " );
scanf("%s",a);
printf("%s\n", a);
}
}
void sigintHandler(int sig_num)
{
signal(SIGINT, sigintHandler);
printf("\n");
loop();
}
int main(int argc, char const *argv[]) {
signal(SIGINT, sigintHandler);
loop();
return 0;
}
Output for code 2:
As can be seen that when I clicked first-time Ctrl+C (on input line 3), it works properly and I can continue. But when I click Ctrl+C second time I don't go to a new line and I have to press enter for a program to execute.
I went through this question but it doesn't seem to apply for my case. This is my first time using signals and system calls so my question may come as silly. But it will be a great help if someone can help me to get to a proper way of implementing signals. Thank you.
Jonathan Leffler provided helpful hints (though not sufficient, at least on some popular operating system):
Look at what scanf() returns.
Don't use loop() in the signal handler
Don't use signal() — use sigaction(). In your case, this has two advantages:
Restoring the signal action to the default state on call of the signal handler can be avoided, so you don't have to change the action again in the handler.
Restarting the read() system call (inside scanf()) can be avoided, so that scanf() returns and you can react to the interrupt in the first place.
So, the signal handler can be just
void sigintHandler(int sig_num)
{
printf("\n"); // or perhaps better write(1, "\n", 1)
}
The signal(SIGINT, sigintHandler); in main() can be replaced with
sigaction(SIGINT, &(struct sigaction){ .sa_handler = sigintHandler }, NULL);
and the scanf("%s",a); with
if (scanf("%s", a) == EOF)
{
if (errno == EINTR) continue; // read operation interrupted by signal
return;
}
EOF is returned on interrupt as well as on end of file, so the cases are to be distinguished through errno. Besides, it's nice if your program provides a way to exit it, thus the return.

How to restore original signal handling properties in C

Tried my best to figure this out on my own, but I really do not want to continue tampering with things that I do not fully understand. So for a programming assignment I have to do in C, I need to terminate a program upon the user entering CTRL+D key stroke via a terminal. I tried to isolate that functionality in a smaller test function, but now my CTRL+D behaves as my CTRL+C and CTRL+C does not have any effect, even outside of the program when it finishes executing. This is the program that caused this change:
#include <unistd.h>
#include <stdio.h>
#include <termios.h>
#include <signal.h>
#include <stdlib.h>
void ctrlD(int sig){
printf("\n");
signal(SIGINT, SIG_DFL);
exit(0);
}
int main(){
signal(SIGINT, ctrlD);
while(1) {
printf("Hello\n");
sleep(5);
}
}
The line signal(SIGINT, SIG_DFL); was added afterward upon realizing my CTRL+C no longer worked. I thought it would return the keystrokes to their original functionalities, but to no avail. What do I do to get back the original functionalities while also making this program work with CTRL+D?
***EDIT: This question seems to have gone off the rails a bit. I get now that Ctrl+D is not a signal. Nonetheless, I no longer have the functionality of Ctrl+C anymore when attempting to use it in my MAC OS terminal, and instead Ctrl+D seems to have that exact functionality. HOW exactly can I return each to have the functionality that they had before I went on this haphazard journey?
If your intention is to restore signal's default behavior after executing handler then, pass SA_RESETHAND flag to sa_flags while registering signal action. For example.
struct sigaction act;
memset(&act, 0, sizeof(struct sigaction));
act.sa_flags = SA_RESETHAND;
act.sa_handler = some_handler;
sigaction(SIGINT, &act, NULL);
From sigaction() man
SA_RESETHAND
Restore the signal action to the default upon entry to the signal handler. This flag is meaningful only when
establishing a signal handler.
If you write a program to explore signals, it is much better to write it carefully, using proper POSIX interfaces (sigaction() instead of signal()), and avoiding undefined behaviour (using non-async-signal safe functions in a signal handler).
Consider, for example, the following program:
#define _POSIX_C_SOURCE 200809L
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <signal.h>
#include <stdio.h>
#include <time.h>
#include <errno.h>
static volatile sig_atomic_t sigint_count = 0;
static void catch_sigint(int signum)
{
if (signum == SIGINT)
sigint_count++;
}
static int install_sigint(void)
{
struct sigaction act;
memset(&act, 0, sizeof act);
sigemptyset(&act.sa_mask);
act.sa_handler = catch_sigint;
act.sa_flags = 0;
if (sigaction(SIGINT, &act, NULL) == -1)
return errno;
return 0;
}
static int install_default(const int signum)
{
struct sigaction act;
memset(&act, 0, sizeof act);
sigemptyset(&act.sa_mask);
act.sa_handler = SIG_DFL;
act.sa_flags = 0;
if (sigaction(signum, &act, NULL) == -1)
return errno;
return 0;
}
int main(void)
{
struct timespec duration;
int result;
if (install_sigint()) {
fprintf(stderr, "Cannot install SIGINT handler: %s.\n", strerror(errno));
return EXIT_FAILURE;
}
duration.tv_sec = 5;
duration.tv_nsec = 0; /* 1/1000000000ths of a second. Nine zeroes. */
printf("Sleeping for %d seconds.\n", (int)duration.tv_sec);
fflush(stdout);
while (1) {
result = nanosleep(&duration, &duration);
if (!result)
break;
if (errno != EINTR) {
fprintf(stderr, "nanosleep() failed: %s.\n", strerror(errno));
return EXIT_FAILURE;
}
/* nanosleep was interrupted by a delivery of a signal. */
if (sigint_count >= 3) {
/* Ctrl+C pressed three or more times. */
if (install_default(SIGINT) == -1) {
fprintf(stderr, "Cannot revert SIGINT to the default handler: %s.\n", strerror(errno));
return EXIT_FAILURE;
}
printf("SIGINT has been reverted to the default handler.\n");
fflush(stderr);
}
}
if (sigint_count > 0)
printf("You pressed Ctrl+C %d time%s.\n", (int)sigint_count, (sigint_count > 1) ? "s" : "");
else
printf("You did not press Ctrl+C at all.\n");
return EXIT_SUCCESS;
}
The #define tells your C library (glibc in particular) that you want POSIX.1-2008 (and later) features from it.
The INT signal handler only increments a volatile sig_atomic_t counter. Note that this type may have a very small range it can represent; 0 to 127, inclusive, should be safe.
The main program waits using the POSIX nanosleep() function. On some systems, sleep() may be implemented via the SIGALRM function, so it is better avoided when using signals otherwise; nanosleep() does not interfere with signals like that at all. Plus, nanosleep() can return the amount of time remaining, if it is interrupted by a signal delivery.
In the main loop, nanosleep() will return 0, if it has slept the entire interval (but note that it may not update the remaining time to 0 in this case). If it is interrupted by the delivery of a signal, it will return -1 with errno == EINTR, and the remaining time updated. (The first pointer is to the duration of the sleep, and the second is to where the remaining time should be stored. You can use the same structure for both.)
Normally, the main loop does only one iteration. It can do more than one iteration, if it is interrupted by the delivery of a signal.
When the main loop detects that sigint_count is at least three, i.e. it has received at least three INT signals, it resets the signal handler back to default.
(Note that both the memset() and the sigemptyset() are important when clearing the struct sigaction structure. The memset() ensures that future code is backwards compatible with older code, by ensuring even padding fields are cleared. And sigemptyset() is the safe way to clear the signal mask (set of signals blocked while the handler runs).)
(In theory, memset() is not async-signal-safe, while both sigemptyset() and sigaction() are. This is why I reset the signal handler in the main program, and not in the signal handler.)
If you want to print from a signal handler, you need to use low-level I/O, because <stdio.h> functions are not async-signal safe. For example, you can use the following function to print strings to standard output:
static int wrerr(const char *p)
{
const int saved_errno = errno;
int retval = 0;
if (p) {
const char *q = p;
ssize_t n;
while (*q)
q++;
while (p < q) {
n = write(STDERR_FILENO, p, (size_t)(q - p));
if (n > 0)
p += n;
else
if (n != -1) {
retval = EIO;
break;
} else
if (errno != EINTR) {
retval = errno;
break;
}
}
}
errno = saved_errno;
return retval;
}
The above wrerr() function is async-signal safe (because it only uses async-signal safe functions itself), and it even keeps errno unchanged. (Many guides forget to mention that it is quite important for a signal handler to keep errno unchanged. Otherwise, when a function is interrupted by a signal handler, and that signal handler modifies errno, the original function will return -1 to indicate an error, but then errno is no longer EINTR!)
You can just use wrerr("INT signal!\n") if you want. The return value from wrerr() is zero if the write was successful, and an errno error code otherwise. It ignores interrupts itself.
Do note that you should not mix stderr output via fprintf() or other <stdio.h> functions with the above (except perhaps for printing error messages when the program aborts). Mixing them is not undefined behaviour, it just may yield surprising results, like wrerr() output appearing in the midst of a fprintf(stderr,...) output.
Its because of exit(0) statement in the handler, when SIGINT is raised, handler strlD gets called and you might thinking why signal(SIGINT,SIG_DFL) didn't work ? Actually it works. But your main process a.out get terminated successfully there itself by calling exit(0). remove exit(0) if you want to restore the behavior of SIGINT.
#include <unistd.h>
#include <stdio.h>
#include <termios.h>
#include <signal.h>
#include <stdlib.h>
void ctrlD(int sig){
//printf("CTRL+C pressed\n");/* just to observe I added one printf
statement, Ideally there shouldn't be any printf here */
signal(SIGINT, SIG_DFL);/*restoring back to original action */
}
int main(){
signal(SIGINT, ctrlD);/*1st time when CTRL+C pressed, handler ctrlD gets called */
while(1) {
printf("Hello\n");
sleep(5);
}
return 0;
}
Also its advisable to use sigaction() instead of signal() as told here What is the difference between sigaction and signal? . Read man 2 sigaction and man 2 exit to check what exit(0) means.
Also this How to avoid using printf in a signal handler?
Edit :
void ctrlD(int sig){
/* printf("CTRL+C pressed \n"); */
signal(SIGINT, SIG_DFL); /* only one time CTRL+C works
after that SIG_DFL will terminate whole process */
}
int main(){
signal(SIGINT, ctrlD); /* if you press CTRL+C then it will go to handler
and terminate */
int ch;
while( ((ch = getchar())!=EOF) ) { /* wait or read char until CTrl+D is not pressed */
printf("Hello : %d \n",ch);/* ASCII equivalent of char */
}
return 0;
}
Thank you everyone who contributed to this question. The resources provided/linked were tremendously helpful in learning more about signals (and that EOF isn't a signal), among the other wealth of information provided.
After some more research, I found out that somehow, either through some accidental bash command gone awry, or perhaps the program posted in my original question itself, I had altered the key mappings for my terminal's stty settings. If anyone finds themselves in this oddly specific situation in the future, I hope this can be of help, as it is what fixed my problem:
Enter the command $ stty -a to see all of your terminals settings, specifically the "cchars" section.
I then saw the reversal, and fixed it like so:
$ stty intr ^C
$ stty eof ^D
Then you can run $ stty -a once again to see that the changes have properly taken effect. Once again, thanks everyone.

Printing in SIGALRM handler

While messing around with system calls for a class, I ran into trouble with the following code. For whatever reason, when the print statement in the signal handler has a newline at the end of it, it behaves as intended, with the signal being received and handled and the message being displayed. However, when the newline is not present, no output is shown at all.
I'm at a loss as to why this might be the case, and was hoping someone could shed some light on the issue.
Further, when it does print something, the signal only seems to be being sent four times? All sorts of strange things with this code.
#include <unistd.h>
#include <stdio.h>
#include <signal.h>
void alarm_handler(int signo) {
printf("pid : %d\n", getpid());
}
int main(int argc, char* argv[]) {
pid_t pid;
signal(SIGALRM, alarm_handler);
pid = fork();
if(pid == 0)
while(1) { }
else
{
int i;
for(i = 0; i < 5; i++)
{
sleep(1);
kill(pid, SIGALRM);
}
kill(pid, SIGKILL);
}
}
GCC Version information
gcc -v
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer//usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 6.0 (clang-600.0.56) (based on LLVM 3.5svn)
Target: x86_64-apple-darwin14.0.0
Thread model: posix
If you for whatever reason want to display something printed without end of line it will most likely help to do fflush(stdout); as stdout is buffered and normally flushes at each end of line.
As pointed out by Henrik Carlqvist in his answer, you observer the effect of "buffered output".
Also SCC mentions in a comment that printf() isn't async signal safe and shall not be called form a signal handler.
To get around 1. and fullfil 2. just write your message using the signal safe function write(), which moreover use unbuffered I/O, so no flushing is needed.
void alarm_handler(int signo)
{
char msg[64] = "alarm handler called";
/* snprintf(msg, sizeof msg, "pid : %d\n", getpid()); */ /* sprintf also isn't async signal safe */
write(fileno(stdout), msg, strlen(msg));
}

Ctrl-C eaten by getchar()

I've been searching for a solution to my problem for a long time now that's why i'm turning to you:
Consider this piece of code:
static char done = 0;
static void sigHandler(void)
{
done = 1;
}
int user_input()
{
return (getchar() == 'q') ? 0 : 1;
}
int main(void)
{
signal(SIGTERM, sigHandler);
signal(SIGINT, sigHandler);
while (user_input() != 0 && !done)
usleep(1000);
printf("exiting\n");
return 0;
}
Expected behavior:
The program exits when user inputs q then enter. If CTRL+C is pressed, it is caught by the sigHandler function which sets the flag 'done' to 1 and exits the program.
Observed behavior:
The CTRL+C character is eaten by the getchar() call, and the sigHandler function is never executed. When CTRL+C and then enter is pressed, the sigHandler function is called and the program exits.
Could someone with more experience and knowledge help me on that one?
Thanks for your input :)
There IS a way to abort the call without resorting to ugly hacks (contrarily to what Paul R said). You should use sigaction() with sa_flags set to 0 instead of signal().
Besides, the signal(2) manual says:
Avoid its use: use sigaction(2) instead.
#include <stdio.h>
#include <signal.h>
#include <string.h>
#include <errno.h>
static char done = 0;
static void sigHandler(int signum)
{
done = 1;
}
int user_input()
{
return (getchar() == 'q') ? 0 : 1;
}
int main(void)
{
struct sigaction sa;
memset(&sa, 0, sizeof(struct sigaction));
sa.sa_handler = sigHandler;
sa.sa_flags = 0;// not SA_RESTART!;
sigaction(SIGINT, &sa, NULL);
sigaction(SIGTERM, &sa, NULL);
while (user_input() != 0 && !done)
usleep(1000);
printf("exiting\n");
return 0;
}
Normally, after catching and handling a signal, most (I'm not sure if not all) syscalls will be restarted. This way, after handling the sigint signal, your getchar function will continue as if nothing happened.
You can change this behavior by calling sigaction with sa_flags=0.
This way, after handling SIGINT, getchar will return -1 and errno will be set to "Interrupted system call" (I don't remember the constant name right now).
You would also have to rewrite your user_input() function to handle the case when returning -1.
The code is actually working as expected - you are not testing the done flag until after you return from user_input(), which is why you need to enter an additional character after the control-C.
If you want to abort the call to getchar when you get a control-C then you'll probably have to do something ugly, e.g. use setjmp/longjmp.
The Ctrl-C character is eaten by the getchar() call, and the sigHandler function is never executed.
Ctrl-C is not eaten by getchar; it results in a signal being delivered and sigHandler being run. This sets done and returns. Only then is getchar called, which eats the newline and after that, done is checked so the program exits.
Btw., a signal handler takes an int argument, not void.

Signal Handling in C

How can I implement signal Handling for Ctrl-C and Ctrl-D in C....So If Ctrl-C is pressed then the program will ignore and try to get the input from the user again...If Ctrl-D is pressed then the program will terminate...
My program follows:
int main(){
char msg[400];
while(1){
printf("Enter: ");
fgets(msg,400,stdin);
printf("%s\n",msg);
}
}
Thanks,
Dave
When dealing with POSIX signals, you have two means at your disposal. First, the easy (but discouraged) way, signal(). Second, the more elegant, current but complex way, sigaction(). Please use sigaction() unless you find that it isn't available on some platform that you need to work on.
This chapter of the glibc manual explains differences between the two and gives good example code on how to use both. It also lists the signals that can be handled, recommends how they should be handled and goes more in depth on how to tell how any given signal is (or is not) currently being handled. That's way more code than I'd want to paste into an answer here, hence the links.
It really is worth the hour or two it would take you to read the links and work through the examples. Signal handling (especially in programs that daemonize) is extremely important. A good program should handle all fatal signals that can be handled (i.e. SIGHUP) and explicitly ignore signals that it might not be using (i.e. SIGUSR1 / SIGUSR2).
It also won't hurt to study the difference between normal and real time signals, at least up to the understanding of how the kernel merges the prior and not the latter.
Once you work through it, you'll probably feel inclined to write up an easy to modify set of functions to handle your signals and re-use that code over and over again.
Sorry for not giving a quick and dirty code snippet to show you how to solve your immediate need, but this isn't a quick and dirty topic :)
Firstly, Ctrl+D is an EOF indicator which you cannot trap, when a program is waiting for input, hitting Ctrl+D signifies end of file and to expect no more input. On the other hand, using Ctrl+C to terminate a program - that is SIGINT, which can be trapped by doing this:
#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
#include <stdarg.h>
static void signal_handler(int);
static void cleanup(void);
void init_signals(void);
void panic(const char *, ...);
struct sigaction sigact;
char *progname;
int main(int argc, char **argv){
char *s;
progname = *(argv);
atexit(cleanup);
init_signals();
// do the work
exit(0);
}
void init_signals(void){
sigact.sa_handler = signal_handler;
sigemptyset(&sigact.sa_mask);
sigact.sa_flags = 0;
sigaction(SIGINT, &sigact, (struct sigaction *)NULL);
}
static void signal_handler(int sig){
if (sig == SIGINT) panic("Caught signal for Ctrl+C\n");
}
void panic(const char *fmt, ...){
char buf[50];
va_list argptr;
va_start(argptr, fmt);
vsprintf(buf, fmt, argptr);
va_end(argptr);
fprintf(stderr, buf);
exit(-1);
}
void cleanup(void){
sigemptyset(&sigact.sa_mask);
/* Do any cleaning up chores here */
}
In your example it seems you don't need CTRL-C handlind at all. A "signal(SIGINT,SIG_IGN)" seems enough for you, unless your application must handle a SIGINT coming from some other source.
CTRL-D doesn't usually generates signals, it simply communicates the EOF condition.
You can in general control the behavior of your terminal (we are talking about console input, it isn't?) by using the termios library (also here). You can enable, redefine or disable the "interrupt" character (CTRL-C), the EOF one and many other ones (XON, XOFF, modem control...)
Regards
This is a program for handling signal when pressed Ctrl+c
The syntax for signal function is : signal(signal name, function name);
#include<stdio.h>
#include<signal.h> // for handling signal
void signal_handler()
{
printf("Signal Handled here\n");
}
main()
{
printf("In main function..\n");
// SIGINT is signal name create when Ctrl+c will pressed
signal(SIGINT,signal_handler);
sleep(15);
printf("In main after called from signal_handle \n");
}
#include<signal.h>
#include<unistd.h>
#include<stdio.h>
void signal_catch()
{
printf("hi,Your signal catched Here");
}
int main()
{
signal(SIGINT,signal_catch);
//press ctrl+c
sleep(10);
return 0;
}//end main
//if you want to simply ignore ctrl+c interrupt use following code in main
int main()
{
signal(SIGINT,SIG_IGN);
sleep(100);
return 0;
}//end main
//this program wont accept ctrl+c interrupt for 100 seconds.

Resources