Reputation: 5
I writing a tiny shell for my subject and I need to catch Ctrl-C and handle it. I have a infinity loop to get user command until they type "exit". When I haven't type Ctrl-C everything is ok, my program get user command and handle it one by one. But when I type Ctrl-C, my program don't get any user command from that time. And I have an infinity loop but I can't type anything except for Ctrl-C.
I try to put a fflush(stdin) begore getline but it doesn't work. I try to list all threads in the process and it is always one. There is always one thread.
#include<iostream>
#include<windows.h>
#include<stdio.h>
#include<stdio.h>
#include<tchar.h>
#include<psapi.h>
#include<vector>
#include<string>
using namespace std;
BOOL WINAPI consoleHandler(DWORD signal)
{
if(signal == CTRL_C_EVENT)
cout << "^C";
return TRUE;
}
int main()
{
SetConsoleCtrlHandler(consoleHandler, TRUE);
string userInput;
while(true)
getline(cin, userInput);
return 0;
}
Expect: After I type CTRL-C console print "^C" and the program will get my next command
Upvotes: 0
Views: 58
Reputation: 8598
Your input stream has an error bit set after Ctrl-C was sent. You need to clear it, otherwise std::getline will not read any characters from the stream and simply return:
BOOL WINAPI consoleHandler(DWORD signal)
{
if (signal == CTRL_C_EVENT)
{
std::cout << "^C\n";
std::cin.clear();
}
return TRUE;
}
Upvotes: 1