管道通信
//服务端 #include <stdio.h> #include <stdlib.h> #include <Windows.h> #define SIZE 4096//缓冲区大小 char pipename[128] = "\\\\.\\Pipe\\cgwpipe";//管道名字 HANDLE m_pipe = NULL;//管道句柄 void start() {
//创建管道 m_pipe = CreateNamedPipeA( pipename,//管道名称 PIPE_ACCESS_DUPLEX,//管道读写属性 PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT,//消息模式,读模式,等待模式阻塞 PIPE_UNLIMITED_INSTANCES,//最大个数 SIZE,//输出缓冲区的大小 SIZE,//输入缓冲区的大小 0,//超时,无限等待 NULL);//安全属性 if (m_pipe == NULL) { printf("创建失败"); return; }
//连接到管道,如果连接到这连接成功 连接不到看得到的错误是不是ERROR_PIPE_CONNECTED BOOL isconnect = ConnectNamedPipe(m_pipe, NULL) ? TRUE : (GetLastError() == ERROR_PIPE_CONNECTED); if (isconnect) { MessageBoxA(0, "connected", "提示", 0); } else { printf("链接失败\n"); } MessageBoxA(0, "服务器启动", "提示", 0); }
//读取 void read() { char buf[SIZE] = { 0 }; int last = 0;//读取的个数 if (!ReadFile(m_pipe, buf, SIZE, &last, NULL)) { printf("服务器读取失败"); return; } printf("\nread=%s", buf); } void write() { char str[128] = "锄禾日当午,管道真他么扯"; int last = 0; BOOL res = WriteFile(m_pipe, str, sizeof(str), &last, NULL); if (!res) { printf("写入失败"); return; } MessageBoxA(0, "服务器写入成功", "提示", 0); } void main() { start(); system("pause"); write(); system("pause"); read(); system("pause"); } //客户端 #include <stdio.h> #include <Windows.h> #define SIZE 4096 char pipename[128] = "\\\\.\\Pipe\\cgwpipe"; HANDLE m_pipe = NULL; void read() { char buf[SIZE] = { 0 }; int last = 0;//读取的个数 if (!ReadFile(m_pipe, buf, SIZE, &last, NULL)) { printf("客户端读取失败"); return; } printf("\nread=%s", buf); } void write() { char str[128] = "客户端也这样认为"; int last = 0; BOOL res = WriteFile(m_pipe, str, sizeof(str), &last, NULL); if (!res) { printf("写入失败"); return; } MessageBoxA(0, "客户端写入成功", "提示", 0); } void main() {
//看能否等到这个管道 if (!WaitNamedPipeA(pipename, NMPWAIT_USE_DEFAULT_WAIT)) { MessageBoxA(0, " cannot connected", "提示", 0); return; }
//CreateFileA 打开管道 m_pipe = CreateFileA(pipename, //名称 GENERIC_WRITE | GENERIC_READ,//权限 读写 1, //共享属性 NULL,//默认安全属性 OPEN_EXISTING,//从已经存在的寻找 FILE_ATTRIBUTE_NORMAL, //默认已经存在的属性 NULL); system("pause"); read(); system("pause"); write(); system("pause"); }