创建或者加载共享内存简单实现

时间:2021-06-25 18:49:44

/******************************************************************************
* 函 数 名:CreateShareMemory
* 函数功能:创建共享内存区域
* 输入说明:iKey ---共享内存KEY值
            iSize ---共享内存大小
     **pAddress --共享内存地址
* 返回值:  返回共享内存地址,失败返回NULL

*******************************************************************************/
void *CreateShareMemory(key_t iKey, size_t iSize,void **pAddress)
{
          int iShmId;

           /*初始化共享内存地址为空*/
          *pAddress = NULL;
   
            //创建共享内存段
           iShmId = shmget( ai_Key,ai_Size,IPC_CREAT | 0666 | SHM_R | SHM_W );
           if  ( iShmId < 0)
           {
                   printf( "shmget function,Create share memory failed!\n" );
                   return NULL;
            }

            //连接共享内存的存储空间
           *pAddress = (void *)shmat(iShmId,NULL,0);
             if  (*pAddress == (void *)-1)
            {
                       printf( "shmat function,Create share memory failed!\n" );
                       return NULL;
             }
 
             /*初始化共享内存*/
             memset(*pAddress,0x00,iSize);
             return *pAddress;
}

 

 

/******************************************************************************
* 函 数 名:LoadShareMemory
* 函数功能:加载共享内存!
* 输入:   iKey------共享内存的KEY值
          pAddress--存放数据的地址
* 返回值:  返回共享内存的地址,失败地址为NULL
*******************************************************************************/
void* LoadShareMemory( key_t iKey,void  **pAddress)
{
       int iShmID;
       *pAddress = NULL; 

         //创建共享内存区域
        iShmID = shmget(iKey,0,SHM_R | SHM_W)
        if  (iShmID < 0)
        {
               printf("Create share memory fail!\n");
               return NULL;
        }

 

         //连接共享内存到相关进程中
        *pAddress = (void *)shmat(iShmID,NULL,0);
          if  (*pAddress == (void *)-1)
          {
                     printf("Load share memory fail!\n");
                     return NULL;
           }

           return( *pAddress );
}

相关文章