C++ 操作共享内存

#include <sys/time.h>
#include <string>
#include <sys/mman.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include<string.h> 
#include<iostream>
using namespace std;
#include <thread>

char* AttachShmBuf(string ringUrl, uint64_t &len)
{
    int fd = open(ringUrl.c_str(), O_RDWR | O_EXCL ,S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);

	if (-1 == fd)
	{
        std::cout << "fd null" <<std::endl;
		return NULL;
	}

	struct stat filestat;
	if((fstat(fd, &filestat)) != 0)
	{
		close(fd);
		fd = 0;
        std::cout << "fstat null" <<std::endl;
		return NULL;
	}

	len  = filestat.st_size;

	char* buf = (char *)mmap(NULL, len, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);

	return buf;
}
void ringfunc(int index)
{
    string filepath= "./ring1m";
    uint64_t len = 0;
    char* pRing =AttachShmBuf(filepath,len);
    if(!pRing)
    {
        std::cout << "ring null" <<std::endl;
        return ;
    } 
    for(;;)
    {
        if(index==0)
        {
            memset(pRing,1,len-1);
        }else
        {
            for(uint64_t i=0;i<len-1;i++)
            {
                char r=pRing[i];
            }  
        }
        std::cout << "index:" << index << " len "<<len  <<std::endl;
        usleep(100);
    }
}

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


    string filepath= "./ring1m";
    uint64_t len = 0;
    char* pRing =AttachShmBuf(filepath,len);
	char* pRing1 =AttachShmBuf(filepath,len);
	char* pRing2 =AttachShmBuf(filepath,len);
    if(!pRing || !pRing1)
    {
        std::cout << "ring null" <<std::endl;
        return 0;
    }
    memset(pRing,0,len);
    int index =0 ;
   
    for(;;)
    {
        memset(pRing,1,len-1);
		//memset(pRing1,2,len-1);
		for(uint64_t i=0;i<len;i++)
		{
			char r=pRing1[i];
		}
		for(uint64_t i=0;i<len/2;i++)
		{
			char r=pRing2[i];
		}
        std::cout << "index:" << index++ << " len "<<len <<std::endl;
        usleep(100);
    }


    for (uint8_t i = 0; i < 4; i++)
    {
        thread t(ringfunc, i);
        t.detach(); 
    }
    getchar();
    std::cout<<"----"<<endl;
    exit(0);

    return 0;
}

  

posted @ 2020-09-09 09:24  苍洱  阅读(520)  评论(0编辑  收藏  举报