IPC – Shared Memory

Inter Process Communication 

Shared Memory


SYSTEM CALL:

shmget() – Used to create a new message queue, or access an existing queue.

Prototype: int shmget ( key_t key, int size, int shmflg );

Returns: shared memory segment identifier on success (or) -1 on error

shmat() – attaches  the shared memory segment identified by shmid to the address space of the calling process.

Prototype: int shmat ( int shmid, char *shmaddr, int shmflg);

Returns: address at which segment was attached to the process, (or) -1 on error


Program :

// 1. IPC Using Shared Memory – Server Program

#include <sys/types.h>

#include <sys/ipc.h>

#include <sys/shm.h>

#include <stdio.h>

#include <stdlib.h>

#define MAXSIZE     27

void die(char *s)

{

perror(s);

exit(1);

}

int main()

{

char c;

int shmid;

key_t key;

char *shm, *s;

key = 5678;

if ((shmid = shmget(key, MAXSIZE, IPC_CREAT | 0666)) < 0)

die(“shmget”);

if ((shm = shmat(shmid, NULL, 0)) == (char *) -1)

die(“shmat”);

s = shm;

for (c = ‘a’; c <= ‘z’; c++)

*s++ = c;

while (*shm != ‘*’)

sleep(1);

exit(0);

}


// 1. IPC Using Shared Memory – Client Program

#include <sys/types.h>

#include <sys/ipc.h>

#include <sys/shm.h>

#include <stdio.h>

#include <stdlib.h>

#define MAXSIZE     27

void die(char *s)

{

perror(s);

exit(1);

}

int main()

{

int shmid;

key_t key;

char *shm, *s;

key = 5678;

if ((shmid = shmget(key, MAXSIZE, 0666)) < 0)

die(“shmget”);

if ((shm = shmat(shmid, NULL, 0)) == (char *) -1)

die(“shmat”);

for (s = shm; *s != ‘\0’; s++)

putchar(*s);

putchar(‘\n’);

*shm = ‘*’;

exit(0);

}