windows pipe

管道分为 匿名管道命名管道
1.匿名管道仅仅能在父子进程间进行通信。不能在网络间通信,并且传输数据是单向的。仅仅能一端写,还有一端读。


2.命令管道能够在随意进程间通信。通信是双向的,随意一端都可读可写,可是在同一时间仅仅能有一端读、一端写。

每个 命名管道 都有一个唯一的名字以区分于存在于系统的命名对象列表中的其它命名管道。管道server在调用CreateNamedPipe()函数创建命名管道的一个或多个实例时为其指定了名称。

对于管道客户机。则是在调用CreateFile()或CallNamedPipe()函数以连接一个命名管道实例时对管道名进行指定。

命名管道的命名规范与邮槽有些相似。对其标识也是採用的UNC格式:

\\Server\Pipe\[Path]Name 

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

服务端使用函数:

CreateNamedPipe(); // 创建管道  
ConnectNamedPipe(); // 堵塞。等待client连接

client使用函数:

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

两方共用函数

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

server端代码演示样例:

#include <stdio.h>  
#include <windows.h>  

#define PIPE_NAME L"\\\\.\\Pipe\\test"  

HANDLE g_hPipe = INVALID_HANDLE_VALUE;  

int main()  
{  
    char buffer[1024];  
    DWORD WriteNum;  

    printf("test server.\n");  
    g_hPipe = CreateNamedPipe(PIPE_NAME, PIPE_ACCESS_DUPLEX, \  
            PIPE_TYPE_BYTE|PIPE_READMODE_BYTE , 1, 0, 0, 1000, NULL);  
    if(g_hPipe == INVALID_HANDLE_VALUE)  
    {  
        printf("Create name pipe failed!\n");  
        goto out;  
    }  

    printf("Wait for connect...\n");  
    if(ConnectNamedPipe(g_hPipe, NULL) == FALSE)  
    {  
        printf("Connect failed!\n");  
        goto out;  
    }  
    printf("Connected.\n");  

    while(1)  
    {  
        scanf("%s", &buffer);  
        if(WriteFile(g_hPipe, buffer, (DWORD)strlen(buffer), &WriteNum, NULL) == FALSE)  
        {  
            printf("Write failed!\n");  
            break;  
        }  
    }  

out:  
    printf("Close pipe.\n");  
    CloseHandle(g_hPipe);  
    system("pause");  
    return 0;  
}  

client代码演示样例:

#include <stdio.h>  
#include <windows.h>  

#define PIPE_NAME L"\\\\.\\Pipe\\test"  

HANDLE g_hPipe = INVALID_HANDLE_VALUE;  

int main()  
{  
    char buffer[1024];  
    DWORD ReadNum;  

    printf("test client.\n");  

    g_hPipe = CreateFile(PIPE_NAME, GENERIC_READ | GENERIC_WRITE,   
            0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);  
    if (g_hPipe == INVALID_HANDLE_VALUE)  
    {  
        printf("Connect pipe failed!\n");  
        goto out;  
    }  
    printf("Connected.\n");  

    while(1)  
    {  
        if(ReadFile(g_hPipe, buffer, sizeof(buffer), &ReadNum, NULL) == FALSE)  
        {  
            break;  
        }  
        buffer[ReadNum] = 0;  
        printf("%s\n", buffer);  
    }  
out:  
    printf("Close pipe.\n");  
    CloseHandle(g_hPipe);  
    system("pause");  
    return 0;  
}  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值