IPC Mechanisms in C: Pipes, FIFO, Shared Memory
IPC Mechanisms in C: Pipes, FIFO, Shared Memory
a) Pipes
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define MSG_LEN 64
int main()
{
int result;
int fd[2];
char message[MSG_LEN];
char recvd_msg[MSG_LEN];
result = pipe (fd);
if (result < 0)
{
pipe
exit(1);
}
strncpy(message, "Linux World!! ", MSG_LEN);
result=write(fd[1],message,strlen(message));
if (result < 0)
{
perror("write");
exit(2);
}
strncpy(message,"Understanding ",MSG_LEN);
result=write(fd[1],message,strlen(message));
if (result < 0)
{
perror("write");
exit(2);
}
strncpy(message,"Concepts of ",MSG_LEN);
result=write(fd[1],message,strlen(message));
if (result < 0)
{
perror("write");
exit(2);
}
Piping
result=write(fd[1],message,strlen(message));
if (result < 0)
{
perror("write");
exit(2);
}
result=read (fd[0], recvd_msg, MSG_LEN);
if (result < 0)
{
perror("read");
exit(3);
}
print("%s\n", recvd_msg);
return 0;
}
Output:
Linux World!! Understanding Concepts of Piping
B) FIFO
#include<stdio.h>
#include<conio.h>
int i,j,nof,nor,flag=0,ref[50],frm[50],pf=0,victm=-1;
void main()
scanf("%d", &nof);
scanf("%d", &nor);
for(i=0;i<nor;i++)
scanf("%d", &ref[i]);
for(i=0;i<nor;i++)
print("%4d", ref[i]);
for(i=1;i<=nof;i++)
frm[i]=-1;
for(i=0;i<nor;i++)
flag=0;
if(frm[j] == ref[i])
flag=1;
break;
}}
if(flag==0)
pf++;
victm++;
victm=victm%nof;
frm[victm]=ref[i];
for(j=0;j<nof;j++)
print("%4d", frm[j]);
getch();
356278
Reference np3-> 3 -1 -1
Reference np5-> 3 5 -1
Reference np6-> 3 5 6
Reference np2-> 2 5 6
Reference np7-> 2 7 6
Reference np8-> 2 7 8
c) Shared Memory
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<sys/types.h>
#define SEGSIZE 100
int main(int argc, char *argv[ ])
{
int shmid, cntr;
key_t key;
char *segptr;
pooja......
key=ftok(".",'s');
if((shmid=shmget(key, SEGSIZE, IPC_CREAT | IPC_EXCL | 0666))== -1)
{
if((shmid=shmget(key,SEGSIZE,0))==-1)
{
perror("shmget");
exit(1);
}
}
else
{
Creating a new shared memory segment
SHMID:%d
}
system("ipcs –m");
if((segptr=(char*)shmat(shmid,0,0))==(char*)-1)
{
perror("shmat");
exit(1);
}
Writing data to shared memory...
strcpy(segptr, buff);
DONE
Reading data from shared memory...
printf("DATA:-%s\n",segptr);
DONE
Removing shared memory Segment...
if(shmctl(shmid, IPC_RMID, 0) == -1)
Can't Remove Shared memory Segment...
else
Removed Successfully
}
Output: