Pipe overwrites buffer, don't know how to overcome
Posted
by
Kalec
on Stack Overflow
See other posts from Stack Overflow
or by Kalec
Published on 2012-06-08T04:36:51Z
Indexed on
2012/06/08
4:40 UTC
Read the original article
Hit count: 390
I use a simple pipe. I read with a while, 1 char at a time, I think every time I read a char I overwrite something
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <string.h>
int main () {
int pipefd[2];
int cpid;
char buf[31];
if (pipe(pipefd) == -1) {
perror("pipe");
exit(EXIT_FAILURE)
}
cpid = fork();
if (cpid == -1) P
perror("cpid");
exit(EXIT_FAILURE);
}
if (cpid == 0) { // child reads from pipe
close (pipefd[1]); // close unused write end
while (read (pipefd[0], &buf, 1)>0);
printf ("Server receives: %s", buf);
close (pipefd[0])l
exit (EXIT_SUCCESS);
}
else { // parent writes to pipe
close (pipefd[0]); // closing unused read end;
char buf2[30];
printf("Server transmits: ");
scanf ("%s", buf2);
write (pipefd[1], buf2, strlen(buf2)+1);
close(pipefd[1]);
wait(NULL);
exit(EXIT_SUCCESS);
}
return 0;
}
For example, if I input: "Flowers" it prints F and then ~6 unprintable characters
© Stack Overflow or respective owner