要求实现:
- 用命名管道的相关知识及函数,分别编写服务器进程和客户端进程程序。
- 要求服务器进程和客户端进程程序能够通过互相传送数据。
- 当服务器进程和客户端进程中的任何一端输入“end”时,结束会话。
写了半天,发现如果只用单个管道的话,非常的困难,进程总是卡住,感觉难点在于服务器进程怎么主动地像客户端进程发送信息,研究了一天还是未解决这个问题。。。
最后是写了个双管道的(每个进程都有各自的服务器和客户端)来实现的,虽然和要求可能有所出入。。。
#include <Windows.h> #include <stdio.h> HANDLE hPipe, hInput; char writeBuffer[256]; char readBuffer[256]; DWORD cbRead = 100; BOOL isSelf = false; BOOL fConnected = false; BOOL isExit = false; DWORD WINAPI mThreadFunc(LPVOID lpParam) { while (true) { gets_s(writeBuffer, 256); if (WaitNamedPipe("\\\\.\\pipe\\test2", 1000)) { CallNamedPipe( "\\\\.\\pipe\\test2", writeBuffer, 256, readBuffer, 256, &cbRead, 20000); printf("%s\n", readBuffer); if (strcmp(writeBuffer, "end") == 0) { exit(-1); } } else { if (GetLastError() == ERROR_FILE_NOT_FOUND) { printf("错误:进程二没在运行!\n"); } } } } int main() { printf("我是进程一。\n\n"); hPipe = CreateNamedPipe( "\\\\.\\pipe\\test1", PIPE_ACCESS_DUPLEX, PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT, 3, 512, 512, 0, NULL); hInput = CreateThread(NULL, 0, mThreadFunc, NULL, 0, NULL); CloseHandle(hInput); while (!isExit) { fConnected = ConnectNamedPipe(hPipe, NULL) ? TRUE : (GetLastError() == ERROR_PIPE_CONNECTED); if (fConnected) { ReadFile(hPipe, readBuffer, 256, 0, NULL); printf("进程二: %s\n", readBuffer); WriteFile(hPipe, "进程一: 我收到了!", 256, 0, NULL); DisconnectNamedPipe(hPipe); if (strcmp(readBuffer, "end") == 0) { isExit = true; } } } CloseHandle(hPipe); return 0; }
#include <Windows.h> #include <stdio.h> HANDLE hPipe, hInput; char writeBuffer[256]; char readBuffer[256]; DWORD cbRead = 100; BOOL isSelf = false; BOOL fConnected = false; BOOL isExit = false; DWORD WINAPI mThreadFunc(LPVOID lpParam) { while (true) { gets_s(writeBuffer, 256); if (WaitNamedPipe("\\\\.\\pipe\\test1", 1000)) { CallNamedPipe( "\\\\.\\pipe\\test1", writeBuffer, 256, readBuffer, 256, &cbRead, 20000); printf("%s\n", readBuffer); if (strcmp(writeBuffer, "end") == 0) { exit(-1); } } else { if (GetLastError() == ERROR_FILE_NOT_FOUND) { printf("错误:进程一没在运行!"); } } } } int main() { printf("我是进程二。\n\n"); hPipe = CreateNamedPipe( "\\\\.\\pipe\\test2", PIPE_ACCESS_DUPLEX, PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT, 3, 512, 512, 0, NULL); hInput = CreateThread(NULL, 0, mThreadFunc, NULL, 0, NULL); CloseHandle(hInput); while (!isExit) { fConnected = ConnectNamedPipe(hPipe, NULL) ? TRUE : (GetLastError() == ERROR_PIPE_CONNECTED); if (fConnected) { ReadFile(hPipe, readBuffer, 256, 0, NULL); printf("进程一: %s\n", readBuffer); WriteFile(hPipe, "进程二: 我收到了!", 256, 0, NULL); DisconnectNamedPipe(hPipe); if (strcmp(readBuffer, "end") == 0) { isExit = true; } } } CloseHandle(hPipe); return 0; }