I want a program which reads a file in the child process and send the string/content to the parent process using simple pipe.
Here is what I have tried, I have read a file and tried to write into the pipe line by line in the while loop. But It doesn't seem to work that way. Your help will be highly appreciated.
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
FILE * fptr;
fptr = fopen(argv[1],"r");
char str1;
int pipefds[2];
char buffer[5];
if(pipe(pipefds) == -1)
{
perror("PIPE ERROR");
exit(EXIT_FAILURE);
}
pid_t pid = fork();
if(pid == 0)
{
char singleLine[150];
close(pipefds[0]);
while(!feof(fptr))
{
fgets(singleLine, 150, fptr);
//puts(singleLine);
write(pipefds[1], singleLine, sizeof(singleLine));
}
fclose(fptr);
//Close read file descriptor
exit(EXIT_SUCCESS);
}
else if(pid > 0)
{
//wait(NULL); //Wait for child process to finish
close(pipefds[1]); //Close write file descriptor
read(pipefds[0], buffer, 100); //Read pin from pipe
close(pipefds[0]); //Close read file descriptor
printf("%s",buffer);
}
return 0;
}