Asynchronous STDIN - windows libraries

Hi!
I'd like to write a program, which makes an infinite loop doing { perform_operations(); sleep(for_minute);}. The program should always monitor the stardard console input, if user inserts a command, program wakes up from his sleep and handles the command.

I wrote the code using Asynchronous I/O multiplexing, however there is one problem: I would like the program to be more server-like, which means that the command is handled (and the program is interrupted) only if user inserts full command and presses enter. The code I wrote, when I do only one keypress holds and waits for message, while I'd rather want it to not stop his loop until enter is pressed.

Here goes the code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <windows.h>
#include <winbase.h>
#include <string>
#include <iostream>
using namespace std;
int main(){

struct _OVERLAPPED over;

ULONG_PTR internal = 0;
ULONG_PTR internalHigh = 0;
PWORD pointer = 0;
over.Internal = internal;
over.InternalHigh = internalHigh;
over.Offset = 0;
over.OffsetHigh = 2000;


struct _SECURITY_ATTRIBUTES secat;
secat.nLength = sizeof (struct _SECURITY_ATTRIBUTES);
    secat.lpSecurityDescriptor = NULL;
    secat.bInheritHandle = FALSE;


    HANDLE conin = CreateFile("CONIN$",//console input
    GENERIC_READ,
    FILE_SHARE_READ,
    &secat,
    OPEN_EXISTING,
    0,
    0);


char bufor[2000];
DWORD i;

HANDLE handle[1];
handle[0]=conin;

while (1){
cout <<"I start my loop...";
DWORD test = WaitForMultipleObjects(  1, handle,  TRUE,  5000);

if (test ==WAIT_TIMEOUT) cout <<" ...Timeout!"<<endl;
else if (test ==WAIT_FAILED) cout <<"error!"<<endl;

else {
for (int ii = 0; ii<2000; ii++) bufor [ii] = '\0';
ReadFile (conin, bufor, 2000, &i, &over);
cout << "I got: " << bufor;
}

}

Could you help me with this one?
Big thanks in advance for any info!
I'm not sure how you intend to interrupt the task you intend to run on timeout.

The loop isn't quite right. Rather than while (true), you might want to consider while (WaitForMultipleObjects, where you'd terminate if a terminate event is signalled. You'd signal it in your Stop Handler.

You can use Overlapped I/O to do the ReadFile. You just add the overlapped event to the list of things to wait for and get signalled when the read completes. When that signals, you check the buffer and process the input command.
Topic archived. No new replies allowed.