Hello, so im trying to make a pipe that use child and parent for reading/writing.
I have a textfile which i get from the argument argv, the parent reads and send every character in the file to the pipe and the child counts the letters from the pipe and prints it.
Is the code in the parent part how I write to a pipe?
Why does my textfile just get appended two times with the already existing text in the file if I do this?
main(int argc, char* argv)
int index = 0, fd, pid, i;
if(argc != 2)
printf("Usage: program <filname>\n");
if(pipe(fd) == -1)
if((pid = fork()) == -1)
if(pid == 0)
int letterCounter = 0;
close(fd); //close unused write end
//read letters from the pipe
while(read(fd, &buffer, sizeof(buffer)) > 0)
for(i = 0 ; i < sizeof(buffer) ; i++)
printf("\n\nChild counting letters: %d\n", letterCounter);
close(fd); //close finished read end
close(fd); //close unused read end
printf("\nParent writing to pipe:\n");
write(fd, &buffer, sizeof(buffer));
close(fd); //close finished write end
wait(NULL); //wait for child to finish, avoid zombies
The output looks like this:
but the text in the file is "this is a textfile 12345"Quote:
Parent writing to pipe:
Child counting letters: 51
Can someone see what I am missing?14