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[1], 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?
Code:
main(int argc, char* argv[])
{
int index = 0, fd[2], pid, i;
char buffer[1024];
if(argc != 2)
{
printf("Usage: program <filname>\n");
exit(0);
}
//pipe
if(pipe(fd) == -1)
{
perror("pipe");
exit(EXIT_FAILURE);
}
//fork
if((pid = fork()) == -1)
{
perror("fork");
exit(EXIT_FAILURE);
}
if(pid == 0)
{
int letterCounter = 0;
close(fd[1]); //close unused write end
//read letters from the pipe
while(read(fd[0], &buffer, sizeof(buffer)) > 0)
{
for(i = 0 ; i < sizeof(buffer) ; i++)
{
if(isalpha(buffer[i]))
{
letterCounter++;
printf("%c", buffer[i]);
}
}
}
printf("\n\nChild counting letters: %d\n", letterCounter);
close(fd[0]); //close finished read end
_exit(EXIT_SUCCESS);
}
else //parent
{
close(fd[0]); //close unused read end
printf("\nParent writing to pipe:\n");
write(fd[1], &buffer, sizeof(buffer));
close(fd[1]); //close finished write end
wait(NULL); //wait for child to finish, avoid zombies
exit(EXIT_SUCCESS);
}
}
The output looks like this:
Parent writing to pipe:
rDBppXbLTPpqPpqPpEnxPdhXiixlTTHhTpHpNXqmkoXNrXpINA L
Child counting letters: 51
but the text in the file is "this is a textfile 12345"
Can someone see what I am missing?14