Unix Shared Memory

来源:互联网 发布:java设备管理系统 编辑:程序博客网 时间:2024/05/09 20:24

To use shared memory, include the following:

#include <sys/types.h>#include <sys/ipc.h>#include <sys/shm.h>

Procedure for using Shared Memory

1. Find a key. Unix uses this key for identifying shared memory segments.

A key is a value of type key_t. There are three ways to generate a key:

a) Do it yourself

key_t SomeKey;SomeKey = 1234;

b) Use function ftok()

key_t = ftok(char *path, int ID);
Keys are global entities. If other process know your key, they can access your shared memory.

c) Ask the system to provide a private key. 

IPC_PRIVATE.

2. Use shmget() to allocate a shared memory.

shm_id = shmget(key_t key,/*identity key */int size,/* memory size */int flag);/* creation or use */
The flag is either 0666(rw) or IPC_CREAT.

The following creates a shared memory of size struct Data with a private key IPC_PRIVATE. This is a creation (IPC_CREAT) and permits read and write(0666).

struct Data{int a;double b;int x;};int ShmID;ShmID = shmget(IPC_PRIVATE,/* private key */sizeof(struct Data),/* size */IPC_CREAT | 0666);/* cr & rw */



3. Use shmat() to attach a shared memory to an address space.


4. Use shmdt() to detach a shared memory from an address space.

5. Use shmctl() to deallocate a shared memory.