VC实现进程间通信(MailSlot附实例)
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 如图:
补充:软件开发 , Vc ,