In: Computer Science
C++ On linux
Write a C++ program using the IPC. Declare two variables a=5 and b=6 in writer process. Now their product (a*b) will be communicated to the reader process along with your name. The reader process will now calculate the square root of the number and display it along with your name.
Named pipes (FIFO) can be used to implement this data transfer.Here are two files writer.cpp and reader.cpp
The files can be compiled using linux commands one by one in following order:
g++ writer.cpp -o write
g++ reader.cpp -o read
./read &
./write &
Writer process file:
/**** WRITER PROCESS FILE *******/
#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
#include<fcntl.h>
#include<sys/stat.h>
#include<string>
int main()
{
int a = 5;
int b = 6;
int mul = a*b;
//its easier ti store data first in string so we have implemented string here
std::string s="";
//to_string(mul) converts mul into string
s+=std::to_string(mul) + " ";
//append s with your name
s+="your name";
//store data to be written into data character array
char data[13];
for(int i=0;i<13;i++)
data[i]=s[i];
// create pipe file
int namedpipe = mkfifo("/tmp/fifo2", 0666); //read write
//open pipe file and store its fd
int fd = open("/tmp/fifo2",O_WRONLY);
//write into file
write(fd,data,sizeof(data));
//close pipe file
close(fd);
return 0;
}
Reader process file:
/**** READER PROCESS FILE *******/
#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
#include<fcntl.h>
#include<sys/stat.h>
#include<string>
#include<math.h>
int main()
{
//variable to store data being read
char buffer[13];
//open pipe file and store its fd
int fd = open("/tmp/fifo2",O_RDONLY);
//read from the file
read(fd,buffer,sizeof(buffer));
//string s is to store integer input i.e. a*b
std::string s="";
int i=0;
while(buffer[i]!=' ' && i<13)
{
s+=buffer[i];
i++;
}
//stoi(s) converts a*b into integer and sqrt calculates square root and store in num
int num = sqrt(stoi(s));
//print num
printf("%d ",num);
//print remaining string i.e. your name
while(i<13)
{
printf("%c",buffer[i]);
i++;
}
//close pipe file
close(fd);
return 0;
}