3 VOID MyErrExit(LPTSTR Message)
5 // MessageBox(NULL, Message, NULL, MB_OK);
10 int main(int argc, char *argv[])
16 DWORD cbRead, cbWritten, dwMode;
17 LPTSTR lpszPipename = "\\\\.\\pipe\\mynamedpipe";
19 // Try to open a named pipe; wait for it, if necessary.
24 lpszPipename, // pipe name
25 GENERIC_READ | // read and write access
28 NULL, // no security attributes
29 OPEN_EXISTING, // opens existing pipe
30 0, // default attributes
31 NULL); // no template file
33 // Break if the pipe handle is valid.
35 if (hPipe != INVALID_HANDLE_VALUE)
38 // Exit if an error other than ERROR_PIPE_BUSY occurs.
40 if (GetLastError() != ERROR_PIPE_BUSY)
41 MyErrExit("Could not open pipe");
43 // All pipe instances are busy, so wait for 20 seconds.
45 if (! WaitNamedPipe(lpszPipename, 20000) )
46 MyErrExit("Could not open pipe");
49 // The pipe connected; change to message-read mode.
51 dwMode = PIPE_READMODE_MESSAGE;
52 fSuccess = SetNamedPipeHandleState(
54 &dwMode, // new pipe mode
55 NULL, // don't set maximum bytes
56 NULL); // don't set maximum time
58 MyErrExit("SetNamedPipeHandleState");
60 // Send a message to the pipe server.
62 lpvMessage = (argc > 1) ? argv[1] : "default message";
66 lpvMessage, // message
67 strlen(lpvMessage) + 1, // message length
68 &cbWritten, // bytes written
69 NULL); // not overlapped
71 MyErrExit("WriteFile");
75 // Read from the pipe.
79 chBuf, // buffer to receive reply
80 512, // size of buffer
81 &cbRead, // number of bytes read
82 NULL); // not overlapped
84 if (! fSuccess && GetLastError() != ERROR_MORE_DATA)
87 // Reply from the pipe is written to STDOUT.
89 if (! WriteFile(GetStdHandle(STD_OUTPUT_HANDLE),
90 chBuf, cbRead, &cbWritten, NULL))
95 } while (! fSuccess); // repeat loop if ERROR_MORE_DATA