Reputation: 31
I'm currently trying to use Ctrl+C to terminate individual while
loops. However when I press Ctrl+C it is currently terminating both while
loops. Is there a way I can make these individual?
This is how I currently have it setup:
volatile sig_atomic_t exitSig = 0;
volatile sig_atomic_t feedExitSig = 0;
void signal_handler(int signum){
exitSig = 1;
livefeedExitSig =1;
}
int main(int argc, char *argv[]){
while (!exitSig){
//complete task
while (!feedExitSig){
//complete task
}
//complete task
}
}
If I press Ctrl+C while I'm in the feedExitSig
loop I want it to only exit that loop and not the exitSig
loop.
Upvotes: 2
Views: 727
Reputation: 84579
In addition to the correct catch by @lenik that signal
is not called registering your signal_handler()
function, you need to only set exitSig
if feedExitSig
is already set. You can do that with a simple conditional in your signal_handler()
, e.g.
void signal_handler(int signum)
{
if (signum == SIGINT) {
if (feedExitSig) /* only if feedExitSig already set */
exitSig = 1; /* set exitSig - requires 2nd ctrl+c */
feedExitSig = 1;
}
}
A complete example requiring Ctrl+c to be pressed to break the inner loop and then pressed again to break the outer loop ending the program could be similar to:
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
volatile sig_atomic_t exitSig = 0;
volatile sig_atomic_t feedExitSig = 0;
void signal_handler(int signum)
{
if (signum == SIGINT) {
if (feedExitSig) /* only if feedExitSig already set */
exitSig = 1; /* set exitSig - requires 2nd ctrl+c */
feedExitSig = 1;
}
}
int main (void) {
signal (SIGINT, signal_handler);
while (!exitSig){
puts ("outer");
while (!feedExitSig){
puts (" inner");
sleep(1);
}
sleep(1);
}
}
Look things over and let me know if you have further questions.
Upvotes: 3
Reputation: 23556
In your main()
you have to use signal(SIGINT, signal_handler);
to let the system know you're about to handle Ctrl/C
presses.
Once that done, you may want to set only one variable in the handler, not both, because right now you're terminating both loops at the same time.
Upvotes: 2