I am looking at how to write pipes and am trying to understand how the standard c library exposes them in some detail. I wrote the following code and would expect that the output would be
2 3
MAJOR ERROR
BYE
However the second line does not show up. Could someone explain why that is happening?
int main()
{
int rc;
int p[2];
char buffer[40];
close(2);
rc = pipe(p);
printf("%d %d\n", p[0], p[1]);
FILE* pipeWrite = fdopen(p[1], "w");
fprintf(pipeWrite, "MAJOR ERROR\n");
close(p[1]);
rc = read(p[0], buffer, 40);
buffer[rc] = '\0';
printf("%s\n", buffer);
printf("BYE\n");
return 0;
}
Thanks.
You are writing into the pipe using standard IO buffered operations (
fprintf(3)), but then close the filedescriptor before flushing output. Addfflush(pipeWrite);immediately before theclose(p[1]);call and see if your output is what you expect. (You could also usefclose(pipeWrite);, as closing the standard IO stream will also flush the output.)See the
setvbuf(3)manpage for more details on the standard IO stream buffering options.