开发者

Why won't this code read the data from the pipe?

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]开发者_如何学Python, 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. Add fflush(pipeWrite); immediately before the close(p[1]); call and see if your output is what you expect. (You could also use fclose(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.


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; }

try

#include <stdio.h>
#include <unistd.h>

int main()
{
    int rc;
    int p[2];
    char buffer[40];

    close(2);

    pipe(p);
    printf("%d %d\n", p[0], p[1]);
    /*    FILE* pipeWrite = fdopen(p[1], "w");
      fprintf(p[1], "MAJOR ERROR\n");*/
    if((rc = write(p[1], "MAJOR ERROR\n", 12)) > 0)
      printf("Wrote to pipe\n");
    close(p[1]);

    if((rc = read(p[0], buffer, 40)) > 0)
      {    buffer[rc] = '\0';
    printf("%s\n", buffer);
    printf("BYE\n");
      }

    return 0;
}

one of many ways to skin a cat

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜