Header Files for Shared Memory
You need to include the following header files
sys/shm.h
and sys/stat.h
Allocate shared memory
int segmentId = shmat (IPC_PRIVATE, size, flags);
where size is an integer telling the size required in bytes
Flags is Oring of things like
IPC_CREAT | IPC_EXCL | SI_IRUSR | SI_IWUSR
(create an exclusive shared memory that can be read from and written to by the current user)Attach to shared memory
char *sharedMem = (char *) shmget (segmentId, 0, 0);
Detatch shared memory
shmdt (sharedMem);
Deallocate shared memory
shmctl (segmentId, IPC_RMID, 0);
Advanced Usage
If you want more control of the shared memory, you need to know
shmctl
better.Determine the segment size
You need a structure to hold segment information. Declare like this
struct shmid_ds buffer
and then use like this
shmctl (segmentId, IPC_STAT, &buffer);
int segmentSize = buffer.shm_segsz;
No comments:
Post a Comment