封装一个SystemV共享内存创建函数

CreateShareMemory具体实现:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
void* CreateShareMemory(unsigned int key, size_t size)
{
    int shm_id = shmget(key, size, IPC_CREAT | IPC_EXCL | 0666);
    if (shm_id < 0) {
        // 创建失败,可能是已有共享内存了
        if (errno != EEXIST) {
            std::clog << "Alloc share memory failed, " 
                << strerror(errno) << std::endl;
            return NULL;
        }
        shm_id = shmget(key, size, 0666);
        if (shm_id < 0) {
            // 如attach失败,可能是size比之前的大
            std::clog << "Attach to share memory " 
                << shm_id << " failed, " << strerror(errno) 
                << ", try to touch it."<< std::endl;
            shm_id = shmget(key, 0, 0666);
            if (shm_id < 0) {
                std::clog << "Fatal error, touch to share memory failed, " 
                    << strerror(errno) << std::endl;
                return NULL;
            } else {
                std::clog << "Remove the exist share memory " 
                    << shm_id << std::endl;
                if (shmctl(shm_id, IPC_RMID, NULL)) {
                    std::clog << "Remove share memory failed, " 
                        << strerror(errno) << std::endl;
                    return NULL;
                }
                shm_id = shmget(key, size, IPC_CREAT | IPC_EXCL | 0666);
                if (shm_id < 0) {
                    std::clog << "Fatal error, alloc share memory failed, " 
                        << strerror(errno) << std::endl;
                    return NULL;
                }
            }
        }
    }
    unsigned char* cur_shm = (unsigned char*)shmat(shm_id, NULL, 0);
    if (!cur_shm) return NULL;
    return cur_shm;
}