EX.
NO: 5
INTER PROCESS COMMUNICATION
DATE:
AIM:
To write a C Program to implement Interprocess Communication using Shared
Memory.
ALGORITM:
smserver.c
1. Start the program.
2. Declare the variables – shmid, key, size.
3. Assign a value for the variable ‘key’.
4. Create a shared memory segment (of size 27 bytes) and obtain access to it.
5. Attach the segment to the data space.
6. Write user input data directly to the segment.
7. Wait until the other process reads the segment and changes the first character of
memory as ‘*’.
8. Stop the program
smclient.c
1. Start the program.
2. Declare the variables – shmid, key, size.
3. Assign a value for the variable ‘key’.
4. Locate the segment created by server.
5. Attach the segment to the data space.
6. Read the data available in the shared memory segment.
7. After reading, change the first character as ‘*’, to indicate the segment has been
read.
8. Stop the program.
PROGRAM:
smserver.c
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#define SHMSIZE 27
int main()
{
char data;
int shmid,i;
key_t key;
char *shm,*s;
key=5678;
47
if((shmid=shmget(key,SHMSIZE,IPC_CREAT | 0666))<0)
{
perror("shmget got failed");
exit(1);
}
if((shm=shmat(shmid,NULL,0))==(char *) -1)
{
perror("shmat got failed");
exit(1);
}
s=shm;
for(i=0;i<60;i++){
scanf("%c",&data);
*s++=data;
*s=NULL;
}
while(*shm != '*')
sleep(1);
exit(0);
}
smclient.c
#include<stdio.h>
#include<stdlib.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<sys/types.h>
#define SHMSIZE 27
main()
{
int shmid;
key_t key=5678;
char *shm, *s;
if((shmid=shmget(key,SHMSIZE,0666))<0)
{
perror("\n Shmget got failed");
exit(1);
}
if((shm=shmat(shmid,NULL,0))==(char*)-1)
{
perror("shmat");
exit(1);
}
for(s=shm;*s!= NULL;s++)
putchar(*s);
putchar('\n');
*shm='*';
exit(0);
}
48
OUTPUT:
RESULT:
The program for Inter-process Communication using Shared Memory was implemented
and verified successfully.
49