How to write a C Program Pipe in C Programming Language ?
Solution:/*C Program Pipe*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main(){
int pfd[2];
if (pipe (pfd) == -1){
printf ("Error in creating pipe!\n");
exit (1);
}
pid_t procID = fork();
if (procID == -1){
printf("Error in creating child!\n");
exit(1);
}
//child
if(procID == 0){
int childNumber = 0;
//citim numarul
read(pfd[0],&childNumber,sizeof(int));
close(pfd[0]);
//calculam rezultatul
int i;
int isPrime = 1;
for(i=2;i<childNumber;i++){
if(childNumber%i==0) isPrime = 0;
}
if(childNumber <=2 ) isPrime = 0;
//scriem rezultatul
write(pfd[1],&isPrime,sizeof(int));
close(pfd[1]);
exit(EXIT_SUCCESS);
}
//parrent
else{
int parrentNumber = 0;
printf("Introduceti numarul: ");
scanf("%d",&parrentNumber);
//scriem numarul
write(pfd[1],&parrentNumber,sizeof(int));
close(pfd[1]);
wait(NULL);
int result;
//citim rezultatul
read(pfd[0],&result,sizeof(int));
close(pfd[0]);
if(result== 1) printf("%d este numar prim! Res: %d\n",parrentNumber,result);
else printf("%d nu este numar prim! Res : %d\n",parrentNumber,result);
exit(EXIT_SUCCESS);
}
}