#include "stdafx.h" #include <stdio.h> #include <windows.h> #include <ctime> int main(int argc, _tchar* argv[]) { srand(time(null)); dword wlen = 0; sleep(1000);//等待pipe的创建成功! bool bret = waitnamedpipe(text("\\\\.\\pipe\\mypipe"), nmpwait_wait_forever); if (!bret) { printf("connect the namedpipe failed!\n"); return 0; } handle hpipe = createfile( //管道属于一种特殊的文件 text("\\\\.\\pipe\\mypipe"), //创建的文件名 generic_read | generic_write, //文件模式 0, //是否共享 null, //指向一个security_attributes结构的指针 open_existing, //创建参数 file_attribute_normal, //文件属性(隐藏,只读)normal为默认属性 null); //模板创建文件的句柄 if (invalid_handle_value == hpipe) { printf("open the exit pipe failed!\n"); } else { while(true) { char buf[256] = ""; sprintf(buf,"%s%d",buf,rand()%1000); if(writefile(hpipe,buf,sizeof(buf),&wlen,0)==false) //向服务器发送内容 { printf("write to pipe failed!\n"); break; } else { printf("to server: data = %s, size = %d\n", buf, wlen); char rbuf[256] = ""; dword rlen = 0; readfile(hpipe, rbuf, sizeof(rbuf), &rlen, 0); //接受服务发送过来的内容 printf("from server: data = %s, size = %d\n", rbuf, rlen); } sleep(1000); } closehandle(hpipe);//关闭管道 } system("pause"); return 0; }
服务端代码:
#include "stdafx.h" #include <stdio.h> #include <windows.h> #include <ctime> int main(int argc, _tchar* argv[]) { srand(time(null)); char buf[256] = ""; dword rlen = 0; handle hpipe = createnamedpipe( text("\\\\.\\pipe\\mypipe"), //管道名 pipe_access_duplex, //管道类型 pipe_type_message|pipe_readmode_message|pipe_wait, //管道参数 pipe_unlimited_instances, //管道能创建的最大实例数量 0, //输出缓冲区长度 0表示默认 0, //输入缓冲区长度 0表示默认 nmpwait_wait_forever, //超时时间 null); //指定一个security_attributes结构,或者传递零值 if (invalid_handle_value == hpipe) { printf("create pipe error(%d)\n",getlasterror()); } else { printf("waiting for client connection...\n"); if(!connectnamedpipe(hpipe, null)) //阻塞等待客户端连接。 { printf("connection failed!\n"); } else { printf("connection success!\n"); } while (true) { if(!readfile(hpipe,buf,256,&rlen,null)) //接受客户端发送过来的内容 { printf("read data from pipe failed!\n"); break; } else { printf("from client: data = %s, size = %d\n", buf, rlen); char wbuf[256] = ""; sprintf(wbuf, "%s%d", wbuf, rand()%1000); dword wlen = 0; writefile(hpipe, wbuf, sizeof(wbuf), &wlen, 0); //向客户端发送内容 printf("to client: data = %s, size = %d\n", wbuf, wlen); sleep(1000); } } flushfilebuffers(hpipe); disconnectnamedpipe(hpipe); closehandle(hpipe);//关闭管道 } system("pause"); return 0; }
以上就是命名管道跨进程通讯的详细内容。