Issue
I have this simple piece of code in a file named printftest.c
.
#include <stdio.h>
int main(){
int c, i;
i = 0;
while ((c = getchar()) != EOF)
++i;
printf("c = %d\n", c);
printf("i = %d\n", i);
}
Compilation and execution is done as follows (on Windows):
gcc printftest.c && a.exe
Terminal session looks like this:
gcc printftest.c && a.exe
c = -1
^C
Now when I give ctrl-c (keyboard interrupt) as input in the terminal only the first printf statement is executed. Why does this happen? I would expect to print both of the statements or none. Can anyone explain where execution stops exactly and why?
Solution
Note, this is how it works on Linux. Windows has something similar. It's not exactly the same, but the basic principle is quite alike. Read more about how it's handled in Windows here: https://learn.microsoft.com/en-us/windows/console/setconsolectrlhandler
When you invoke C-C, the kernel will send a SIGINT to the program. Unless this signal is handled by the program, it will be killed.
This is done asynchronously. It basically looks like this:
1) User: C-C
2) Kernel: Hey program, do you hear me? I will kill you if you don't answer.
3) Kernel: The program does not seem to hear me. Let's kill it.
What happens between 2 and 3 is a bit of a gamble. A SIGINT is usually used to say to the program that the user have been tired of waiting for whatever the program is doing. The kernel will only forcefully kill the program if it does not handle the SIGINT, but it has no requirements on how to handle it.
If you want the behavior to be well defined, you have to install a handler. Here is an example of how you can modify your program (in Linux) to ignore C-C completely:
#include <signal.h>
void install_handler()
{
static struct sigaction sigact = { 0 };
sigact.sa_handler = SIG_IGN;
sigaction(SIGINT, &sigact, NULL);
}
int main()
{
install_handler()
// Your code
Answered By - klutt Answer Checked By - Mildred Charles (PHPFixing Admin)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.