3

I wrote this simple program:

void sig_ha(int signum)
{
cout<<"received SIGINT\n";
}

int main()
{
 string name;
 struct sigaction newact, old;
 newact.sa_handler = sig_ha;
 sigemptyset(&newact.sa_mask);
 newact.sa_flags = 0;
 sigaction(SIGINT,&newact,&old);

 for (int i=0;i<5;i++)
     {
     cout<<"Enter text: ";
     getline(cin,name);
     if (name!="")
         cout<<"Text entered: "<<name;
     cout<<endl;
     }
 return 0;
}

If I hit Ctrl+C while the program waits for input I get the following output:
Enter text: received SIGINT

Enter text:
Enter text:
Enter text:
Enter text:

(the program continues the loop without waiting for input)

What should I do?

Josh Correia
  • 3,807
  • 3
  • 33
  • 50
ThP
  • 2,312
  • 4
  • 19
  • 25
  • Can you describe exactly what you are trying to achieve? Usually for a simple program it is easier to let the signals have the expected effect, i.e. for SIGINT, terminate the program. Also, depending on your system it may not be safe to use high level io (such as std::cout) from a signal handler. – CB Bailey Nov 21 '09 at 11:47
  • I'm trying to write a small shell program. this is just an example to help me describe my problem. – ThP Nov 21 '09 at 12:12

1 Answers1

4

Try adding the following immediately before your cout statement:

cin.clear();  // Clear flags
cin.ignore(); // Ignore next input (= Ctr+C)
Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • Can't use `ignore()` because I don't know when the user will send SIGINT but `clear()` works good enough I think. thank you! – ThP Nov 21 '09 at 12:15