I have this code
int main() {
int fd[2];
pipe(fd);
dup2(fd[1], 1); close(fd[1]);
printf("I wanna print this.");
char * buf = malloc(100);
read(fd[0], buf, 50);
fprintf(stderr, ">>>%s<<<\n", buf);
close(fd[0]);
}
Expected output : print >>>I wanna print this.<<< on stderr
How can I make this work?
The main problem is that the line you printed got buffered, so it didn't actually get sent to the pipe. Either do
fflush(stdout);somewhere between yourprintfandreadto flush the buffer, or disable buffering ofstdoutwithsetbuforsetvbufat the very beginning of your program.A secondary problem is that you're mixing up counted and null-terminated strings, as Jonathan Leffler alluded to in the comments.