:pserver:cvsanon@mok.lvcm.com:/CVS/ReactOS reactos
[reactos.git] / apps / tests / nptest / npclient.c
1 #include <windows.h>
2
3 VOID MyErrExit(LPTSTR Message)
4 {
5 //      MessageBox(NULL, Message, NULL, MB_OK);
6    puts(Message);
7    ExitProcess(0);
8 }
9
10 int main(int argc, char *argv[])
11 {
12    HANDLE hPipe;
13    LPVOID lpvMessage;
14    CHAR chBuf[512];
15    BOOL fSuccess;
16    DWORD cbRead, cbWritten, dwMode;
17    LPTSTR lpszPipename = "\\\\.\\pipe\\mynamedpipe";
18
19 // Try to open a named pipe; wait for it, if necessary.
20
21    while (1)
22    {
23       hPipe = CreateFile(
24          lpszPipename,   // pipe name
25          GENERIC_READ |  // read and write access
26          GENERIC_WRITE,
27          0,              // no sharing
28          NULL,           // no security attributes
29          OPEN_EXISTING,  // opens existing pipe
30          0,              // default attributes
31          NULL);          // no template file
32
33    // Break if the pipe handle is valid.
34
35       if (hPipe != INVALID_HANDLE_VALUE)
36          break;
37
38       // Exit if an error other than ERROR_PIPE_BUSY occurs.
39
40       if (GetLastError() != ERROR_PIPE_BUSY)
41          MyErrExit("Could not open pipe");
42
43       // All pipe instances are busy, so wait for 20 seconds.
44
45       if (! WaitNamedPipe(lpszPipename, 20000) )
46          MyErrExit("Could not open pipe");
47    }
48
49 // The pipe connected; change to message-read mode.
50
51    dwMode = PIPE_READMODE_MESSAGE;
52    fSuccess = SetNamedPipeHandleState(
53       hPipe,    // pipe handle
54       &dwMode,  // new pipe mode
55       NULL,     // don't set maximum bytes
56       NULL);    // don't set maximum time
57    if (!fSuccess)
58       MyErrExit("SetNamedPipeHandleState");
59
60 // Send a message to the pipe server.
61
62    lpvMessage = (argc > 1) ? argv[1] : "default message";
63
64    fSuccess = WriteFile(
65       hPipe,                  // pipe handle
66       lpvMessage,             // message
67       strlen(lpvMessage) + 1, // message length
68       &cbWritten,             // bytes written
69       NULL);                  // not overlapped
70    if (! fSuccess)
71       MyErrExit("WriteFile");
72
73    do
74    {
75    // Read from the pipe.
76
77       fSuccess = ReadFile(
78          hPipe,    // pipe handle
79          chBuf,    // buffer to receive reply
80          512,      // size of buffer
81          &cbRead,  // number of bytes read
82          NULL);    // not overlapped
83
84       if (! fSuccess && GetLastError() != ERROR_MORE_DATA)
85          break;
86
87       // Reply from the pipe is written to STDOUT.
88
89       if (! WriteFile(GetStdHandle(STD_OUTPUT_HANDLE),
90          chBuf, cbRead, &cbWritten, NULL))
91       {
92          break;
93       }
94
95    } while (! fSuccess);  // repeat loop if ERROR_MORE_DATA
96
97    CloseHandle(hPipe);
98
99    return 0;
100 }