windows 命名管道

个人感觉,windows 下的命名管道忒难用。

每一个命名管道都有一个唯一的名字以区分于存在于系统的命名对象列表中的其他命名管道。管道服务器在调用CreateNamedPipe()函数创建命名管道的一个或多个实例时为其指定了名称。对于管道客户机,则是在调用CreateFile()或CallNamedPipe()函数以连接一个命名管道实例时对管道名进行指定。命名管道的命名规范与邮槽有些类似,对其标识也是采用的UNC格式:

\ServerPipe[Path]Name  

其中,第一部分\Server指定了服务器的名字,命名管道服务即在此服务器创建,其字串部分可表示为一个小数点(表示本机)、星号(当前网络字段)、域名或是一个真正的服务;第二部分Pipe与邮槽的Mailslot一样是一个不可变化的硬编码字串,以指出该文件是从属于NPFS;第三部分[Path]Name则使应用程序可以唯一定义及标识一个命名管道的名字,而且可以设置多级目录。

服务端使用函数:

CreateNamedPipe(); // 创建管道
ConnectNamedPipe(); // 阻塞,等待客户端连接

  客户端使用函数:

CreateFile(); // 打开(连接)管道

双方共用函数:

WriteFile();
ReadFile(); // 阻塞,使用方便
CloseHandle(); // 关闭管道,断开连接

服务端例程:

 1 #include <stdio.h>
 2 #include <windows.h>
 3 
 4 #define PIPE_NAME L"\\.\Pipe\test"
 5 
 6 HANDLE g_hPipe = INVALID_HANDLE_VALUE;
 7 
 8 int main()
 9 {
10     char buffer[1024];
11     DWORD WriteNum;
12 
13     printf("test server.
");
14     g_hPipe = CreateNamedPipe(PIPE_NAME, PIPE_ACCESS_DUPLEX, 
15             PIPE_TYPE_BYTE|PIPE_READMODE_BYTE , 1, 0, 0, 1000, NULL);
16     if(g_hPipe == INVALID_HANDLE_VALUE)
17     {
18         printf("Create name pipe failed!
");
19         goto out;
20     }
21     
22     printf("Wait for connect...
");
23     if(ConnectNamedPipe(g_hPipe, NULL) == FALSE)
24     {
25         printf("Connect failed!
");
26         goto out;
27     }
28     printf("Connected.
");
29 
30     while(1)
31     {
32         scanf("%s", &buffer);
33         if(WriteFile(g_hPipe, buffer, (DWORD)strlen(buffer), &WriteNum, NULL) == FALSE)
34         {
35             printf("Write failed!
");
36             break;
37         }
38     }
39 
40 out:
41     printf("Close pipe.
");
42     CloseHandle(g_hPipe);
43     system("pause");
44     return 0;
45 }

客户端例程:

 1 #include <stdio.h>
 2 #include <windows.h>
 3 
 4 #define PIPE_NAME L"\\.\Pipe\test"
 5 
 6 HANDLE g_hPipe = INVALID_HANDLE_VALUE;
 7 
 8 int main()
 9 {
10     char buffer[1024];
11     DWORD ReadNum;
12 
13     printf("test client.
");
14 
15     g_hPipe = CreateFile(PIPE_NAME, GENERIC_READ | GENERIC_WRITE, 
16             0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
17     if (g_hPipe == INVALID_HANDLE_VALUE)
18     {
19         printf("Connect pipe failed!
");
20         goto out;
21     }
22     printf("Connected.
");
23 
24     while(1)
25     {
26         if(ReadFile(g_hPipe, buffer, sizeof(buffer), &ReadNum, NULL) == FALSE)
27         {
28             break;
29         }
30         buffer[ReadNum] = 0;
31         printf("%s
", buffer);
32     }
33 out:
34     printf("Close pipe.
");
35     CloseHandle(g_hPipe);
36     system("pause");
37     return 0;
38 }
原文地址:https://www.cnblogs.com/habibah-chang/p/3540400.html