AIM : To implement inter-process communication using shared memory
ALGORITHM :
step 1 : start
step 2 : declare shid, pid as integer and *msg as char
step 3 : get the shid of existing shared memory using shmget()
step 4 : attach the existing shared memory to address using shmat()
step 5 : create a process using fork()
step 6 : if it is a parent process then do
a) read the message
b) write it to shared memory
step 7 : if it is a child process then read the message from shared memory and print it.
step 8 : stop
PROGRAM :
#include<stdio.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<sys/unistd.h>
int main()
{
int pid, shid;
char *msg;
shid = shmget(IPC_PRIVATE,1,IPC_CREAT|0666);
msg = shmat(shid,0,0);
pid = fork();
if(pid>0)
{
printf("PARENT PROCESS");
printf("\n enter the message to child : ");
scanf("%s",msg);
printf("\n message is written into the shared memory by parent");
}
if(pid == 0)
{
sleep(6);
printf("\n CHILD PROCESS");
printf("\n child reads the message %s : ",msg);
}
exit(0);
}
OUTPUT
compile : gcc filename.c
run : ./a.out
enter the message to child : mother
control in parent process
message is written into the shared memory by parent
control in child process
child reads the message
mother
ALGORITHM :
step 1 : start
step 2 : declare shid, pid as integer and *msg as char
step 3 : get the shid of existing shared memory using shmget()
step 4 : attach the existing shared memory to address using shmat()
step 5 : create a process using fork()
step 6 : if it is a parent process then do
a) read the message
b) write it to shared memory
step 7 : if it is a child process then read the message from shared memory and print it.
step 8 : stop
PROGRAM :
#include<stdio.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<sys/unistd.h>
int main()
{
int pid, shid;
char *msg;
shid = shmget(IPC_PRIVATE,1,IPC_CREAT|0666);
msg = shmat(shid,0,0);
pid = fork();
if(pid>0)
{
printf("PARENT PROCESS");
printf("\n enter the message to child : ");
scanf("%s",msg);
printf("\n message is written into the shared memory by parent");
}
if(pid == 0)
{
sleep(6);
printf("\n CHILD PROCESS");
printf("\n child reads the message %s : ",msg);
}
exit(0);
}
OUTPUT
compile : gcc filename.c
run : ./a.out
enter the message to child : mother
control in parent process
message is written into the shared memory by parent
control in child process
child reads the message
mother
No comments:
Post a Comment