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.

