Implementation of Shared Memory Segment


//Shared Memory Segment

Program 1:

#include <sys/types.h>

#include <sys/ipc.h>

#include <sys/shm.h>

#include <stdio.h>

#include <sys/sem.h>

#define SHMSZ     27

main()

{

char c;

int semid,retval;

struct sembuf sop,sop1;

int shmid;

key_t key;

char *shm, *s;

key = 5678;

semid=semget(20,1,0666|IPC_CREAT);

semctl(semid,0,SETVAL,1);

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

{

perror(“shmget”);

exit(1);

}

else

{

printf(“\n\n\t Shared memory Get Success. “);

printf(“\n\n\t ID : %d , KEY : %d , SIZE : %d”,shmid,key,SHMS

}

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

{

perror(“shmat”);

exit(1);

}

sop.sem_num=0;

sop.sem_op=-1;

sop.sem_flg=0;

semop(semid,&sop,1);

s = shm;

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

*s++ = c;

*s = ”;

sop1.sem_num=0;

sop1.sem_op=1;

sop1.sem_flg=0;

semop(semid,&sop1,1);

while (*shm != ‘*’)

sleep(1);

printf(“\n\n\t server exited”);

shmctl(shmid,IPC_RMID,NULL);

semctl(semid,0,IPC_RMID);

exit(0);

}

Program 2:

#include <sys/types.h>

#include <sys/ipc.h>

#include <sys/shm.h>

#include <stdio.h>

#include <sys/sem.h>

#define SHMSZ     27

main()

{

FILE *fp;

int shmid,semid;

struct sembuf sop,sop1;

key_t key;

char *shm, *s,tmp;

key = 5678;

semid=semget(20,1,0666|IPC_CREAT);

semctl(semid,0,SETVAL,1);

fp=fopen(“shm1.txt”,”w”);

perror(“shmget”);

exit(1);

}

else

{

printf(“\n\n\t shmget_succeed”);

printf(“\n\n\t ID : %d, SIZE : %d, KEY : %d”,shmid,SHMSZ,key);

}

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

{

perror(“shmat”);

exit(1);

}

else

printf(“\n\n\t shmat_succeed \n\n”);

sop.sem_num=0;

sop.sem_op=-1;

sop.sem_flg=0;

semop(semid,&sop,1);

for (s = shm; *s != ”; s++)

{

tmp=*s;

putchar(*s);

fprintf(fp,”%c”,tmp);

}

putchar(”);

*shm = ‘*’;

sop1.sem_num=0;

sop1.sem_op=1;

sop1.sem_flg=0;

semop(semid,&sop1,1);

fclose(fp);

printf(“\n\n\t Client Exited”);

shmctl(shmid,IPC_RMID,NULL);

semctl(semid,0,IPC_RMID);

exit(0);

}

Advertisements