VC实现进程间通信(MailSlot附实例)

本文提供了一个基于Windows系统的邮路通信实现案例,包括服务器端和客户端代码。通过创建邮路进行消息收发,展示了如何使用CreateMailslot及CreateFile等API函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

By 闲鸟归来

01 // ...Server
02 #include <windows.h>
03 #include <stdio.h>
04 
05 /* 创建邮路由:
06 HANDLE CreateMailslot (
07                           LPCTSTR lpName,                            // 邮路名
08                           DWORD nMaxMessageSize,                     // 消息最大的大小
09                           DWORD lReadTimeout,                        // 读取操作的超时时间
10                           LPSECURITY_ATTRIBUTES lpSecurityAttributes // 描述安全信息的一个结构
11                       );
12 */
13 
14 /* 删除邮路由:
15 BOOL CloseHandle (
16                     HANDLE hObject   // 邮路句柄
17                  );
18 */
19 
20 /************************************************************************/
21 /*    其它邮路函数简介如下:                                                */
22 /*  GetMailslotInfo:获取指定邮路的相关信息;                            */
23 /*    SetMailslotInfo:设置指定邮路的相关信息;                            */
24 /************************************************************************/
25 
26 
27 int main(int argc, char* argv[])
28 {
29     char szMailAddr[] = "\\.\Mailslot\mailslot_abc";
30     HANDLE hMailslot;
31     char buffer[1024];
32     
33     hMailslot = CreateMailslot(szMailAddr, 0, MAILSLOT_WAIT_FOREVER, NULL);
34     if(hMailslot == INVALID_HANDLE_VALUE)
35     {
36        printf("创建邮件槽失败%lu ", GetLastError());
37        return 1;
38     }
39     DWORD dwReadBytes = 0;
40     memset(buffer, 0, 1024);
41     while(ReadFile(hMailslot, buffer, 1022, &dwReadBytes, NULL))
42     {
43        printf("%s ", buffer);
44     }
45     return 0;
46 }
47 
48 // ...Client
49 #include <windows.h>
50 #include <stdio.h>
51 
52 int main(int argc, char* argv[])
53 {
54     char szMailAddr[] = "\\.\Mailslot\mailslot_abc";
55     HANDLE hFile;
56     char buffer[1024];
57     
58     hFile = CreateFile(szMailAddr, GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
59     if(hFile == INVALID_HANDLE_VALUE)
60     {
61        printf("failed to create file %s ", szMailAddr);
62        return 1;
63     }
64 
65     DWORD dwWriteBytes;
66     for(int i = 1; i <= 100; i++)
67     {
68        sprintf(buffer, "Send message to server the index is = %d", i);
69        WriteFile(hFile, buffer, strlen(buffer) + 1, &dwWriteBytes, NULL);
70     }
71     return 0;
72 }
73 如图:
\


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值