Shared memory

advertisement
CS 3100
Operating Systems
Fall 2003
Shared memory in a local UNIX/Linux domain
The following example demonstrates the use of shared memory between independent Unix processes in a local
domain. The system calls used are;
 int shmget (int key, int size, int mode); Returns an integer ID for a persistent block of shared memory of
size bytes. Key is a publicly known positive integer key by which all processes will get access to the shared
memory block. (A key of IPC_PRIVATE produces a temporary block that is only available for this process
and any forked children. The mode parameter specifies read/write priveledge in a manner similar to files.
 char *shmat (int shmid, 0, 0); Used to attach a shared memory block to a local address pointer. Returns the
address of the shared memory block associated with shmid. Returns an error code (<0) if unsuccessful.
The parameter types and options are documented in associated man pages, but the following example demonstrates
the creation and access of a single shared memory block of 64 bytes.
/* shm_test.c: demo of shared memory */
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#define SIZE 64
void main()
{ int shmid, n;
char *buf, c;
printf (“enter shared memory key: “);
scanf (“%d”, &semid);
semid = shmget (key, SIZE, 0666 | IPC_CREAT);
/* read/write access for all */
/* create it if it doesn’t
exist */
buf = shmat (semid, 0, 0);
shared memory block */
while (1)
{ printf (“enter index and value: “);
loop */
scanf (“%d %c”, %n, &c);
buf[n] = c;
*/
}
}
/* buf now points to
/* simple demonstration
/* store in shared memory
In another independent program executed after the above program has started or run...
...
semid = shmget (key, SIZE, 0666);
buf = shmat (semid, 0, 0);
while (1)
{ printf (“enter index to examine: “);
scanf (“%d”, &n);
printf (“memory value: %c\n”, buf[n]);
}
533574313
03/08/16
CS 3100
Operating Systems
Fall 2003
Shared memory is persistent (except for IPC_PRIVATE blocks). Existing blocks can be listed using the ipcs command and removed with the ipcrm command similar to semaphores and message queues.
533574313
03/08/16
Download