sharememory

Identifiers and Keys

Identifiers: Each IPC structure(message queue, semaphore, or share memory segment) is referred to by a non-negative integer identifier. 主要用于send/fetch the content from the IPC structure.
需要注意The identifier is an internal name for an IPC object. 在Cooperating processes之间,就需要an external namin scheme, 也就是key。

在创建IPC structure时,需要指定key,比如

1
extern int  (key_t __key, size_t __size, int __shmflg) __THROW;

那么怎么来获取key呢?

  1. The server can create a new IPC structure by specifying a key of IPC_PRIVATE and store the returned identifier somewhere(such as a file ) for the client to obtain.
    注意通过key IPC_PRIVATE 只能用于create a new IPC structure, 后续无法通过这个key来access IPC structure.
    IPC_PRIVATE key 也用在parent-child relationship. 在parent中create IPC structure, 这个Identifier is available in child process after fork(). 在child process会获取parent data的副本
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

#include <sys/ipc.h>
#include <iostream>
#include <string>
#include <errno.h>
#include <unistd.h>

int main(int argc, char ** argv)
{
int id = shmget(IPC_PRIVATE, 1024, IPC_CREAT | IPC_EXCL | 0666);
pid_t child = fork();
if(child == 0)
{
std::cout << "id in child is " << id << std::endl;
exit(0);
}

std::cout << "id in parent is " << id << std::endl;
exit(0);
}
  1. The client and the server can agree on a key by defining the key in a common header
  2. ftok
    1
    2
    #include <sys/ipc.h> 
    key_t ftok(const char *path, int id);