Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1109689
  • 博文数量: 284
  • 博客积分: 8223
  • 博客等级: 中将
  • 技术积分: 3188
  • 用 户 组: 普通用户
  • 注册时间: 2008-12-01 13:26
文章分类

全部博文(284)

文章存档

2012年(18)

2011年(33)

2010年(83)

2009年(147)

2008年(3)

分类: C/C++

2009-10-11 19:52:23

    废话少说,直接切入正题,本代码实现的是多线程下的邮槽服务进程。跟上一次提到的邮槽相比,多了多线程相关的代码。
 
服务进程:
 

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

BOOL StopProcessing;

DWORD WINAPI ServeMailslot(LPVOID lpParameter);
void SendMessageToMailslot(void);

int main(int argc, char* argv[])
{

    DWORD ThreadId;
    HANDLE MailslotThread;

    StopProcessing=FALSE;
    MailslotThread=CreateThread(NULL,0,ServeMailslot,NULL,0,&ThreadId);
    printf("Press a key to stop the server\n");
    _getch();
    StopProcessing=TRUE;
 
    if(WaitForSingleObject(MailslotThread,INFINITE)==WAIT_FAILED)
    {
        printf("WaitForsingleObject failed with error %d\n",GetLastError());
        return 1;
    }

    return 0;
}

DWORD WINAPI ServeMailslot(LPVOID lpParameter)
{
    char buffer[2048];
    DWORD NumberOfBytesRead;
    DWORD Ret;
    HANDLE Mailslot;
    
    memset(buffer,0,2048);
    if((Mailslot=CreateMailslot(_T("\\\\.\\mailslot\\myslot"),2048,MAILSLOT_WAIT_FOREVER,NULL))==INVALID_HANDLE_VALUE)
    {
        printf("Failed to create a Mailslot %d\n",GetLastError());
        return 0;
    }
    while((Ret=ReadFile(Mailslot,buffer,2048,&NumberOfBytesRead,NULL))!=0)
    {
     if(StopProcessing)
        break;
        printf("Received %d bytes \n",NumberOfBytesRead);
        printf("Data:%s\n",buffer);
    }
    CloseHandle(Mailslot);
    return 0;
}


客户进程:

#include <windows.h>
#include <stdio.h>
#include <TCHAR.h>
              
void main(int argc, char *argv[])
{
   HANDLE Mailslot;
   DWORD BytesWritten;
   char ServerName[256];
        
                     // Accept a command line argument for the server to sen

                                       
  if ((Mailslot = CreateFile(_T("\\\\.\\Mailslot\\Myslot"), GENERIC_WRITE,
    FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL,
    NULL)) == INVALID_HANDLE_VALUE)
  {
      printf("CreateFile failed with error %d\n", GetLastError());
      return;
   }
                   
   if (WriteFile(Mailslot, "i am toy", 14, &BytesWritten, NULL) == 0)
   {
      printf("WriteFile failed with error %d\n", GetLastError());
      return;
   }
   printf("Wrote %d bytes \n", BytesWritten);
   CloseHandle(Mailslot);
}


    注意在vs2008上编译后,执行时,会报找不到MSVCR90D.dll。这个是微软自己的问题,网上搜了下,好象跟分区FAT32和NTFS有关系,只要将编译debug版本修改为release版就可以跳过这个错误。
阅读(803) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~