Try this:
#include <Windows.h>
#include <iostream>
DWORD waitThread(HANDLE hThread) {
DWORD dwTimeOut{ 10000 };
const char* emsg{};
switch (WaitForSingleObject(hThread, dwTimeOut))
{
case WAIT_OBJECT_0:
return true;
case WAIT_TIMEOUT:
emsg = "WAIT_TIMEOUT";
break;
case WAIT_ABANDONED:
emsg = "WAIT_ABANDONED";
break;
case WAIT_FAILED:
emsg = "WAIT_FAILED";
break;
}
std::cout << "WaitForSingleObject: Error " << emsg << std::endl;
return false;
}
DWORD WINAPI threadFileOperations(LPVOID lpParam)
{
HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
HANDLE hStdIn = GetStdHandle(STD_INPUT_HANDLE);
LPCSTR lpszPrompt1{ "Option: " };
DWORD dwBytesWritten{ 0 };
DWORD dwBytesRead{ 0 };
char* readBuffer = reinterpret_cast<char*>(lpParam);
if (hStdOut == INVALID_HANDLE_VALUE || hStdIn == INVALID_HANDLE_VALUE) {
std::cout << "I/O Handles: Error " << GetLastError() << std::endl;
return 1;
}
if (!WriteFile(
hStdOut,
lpszPrompt1,
lstrlen(lpszPrompt1),
&dwBytesWritten,
NULL)) {
std::cout << "WriteFile: Error " << GetLastError() << std::endl;
return 1;
}
if (!ReadFile(
hStdIn,
readBuffer,
250,
&dwBytesRead,
NULL)) {
std::cout << "ReadFile: Error " << GetLastError() << std::endl;
return 1;
}
return 0; }
int main() {
HANDLE hThread{};
DWORD dwThreadId{};
CHAR chBuffer[251]{};
while (hThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)threadFileOperations,
chBuffer, 0, &dwThreadId))
{
if (!waitThread(hThread))
{
return 1;
}
switch (chBuffer[0]) {
case '1': std::cout << "hello option 1" << std::endl;
break;
case '2': std::cout << "hello option 2" << std::endl;
break;
case '3': std::cout << "hello option 3" << std::endl;
break;
case '4': std::cout << "hello option 4" << std::endl;
break;
case '5': std::cout << "exit loop" << std::endl;
ExitProcess(0);
default: std::cout << "invalid option" << std::endl;
break;
}
CloseHandle(hThread);
}
return 0;
}
The main point is that you need to call the thread process each time before checking the input value. And on return you must wait for the thread to terminate. If it is successful then you can check the value in the input buffer. If the thread terminates abnormally then the program closes.