Read / Write through a pipe in C

前端 未结 2 598
醉话见心
醉话见心 2020-12-21 08:23

I started today working with pipe() and fork() and exec() in C, and I now have a problem:

The main program, creates two pipes and forks. The child process does an ex

相关标签:
2条回答
  • 2020-12-21 09:00

    After read, you need to add terminating 0 byte at the end, before printing, something like

    int len = read(select[0], buffer, sizeof(buffer) - 1);
    if (len < 0) {
        perror("read error");
    } else {
        buffer[len] = 0;
        printf("Buffer recived: %s\n", buffer);
    }
    

    So, imporant thing, read through man page of read, or actually man page of any function before you use it...

    Alternatively, use some stdio.h function, which adds string terminating 0 themselves, probably fgets if reading line by line is ok.

    0 讨论(0)
  • 2020-12-21 09:01

    pipes don't keep track of 'boundaries' between writes. So if you have multiple writes on the pipe, all the data from those writes might come back in response to a single read. So if you send a string (for example) followed by an integer, and you attempt to read the string into a buffer, it will get both the string and the following integer integer into the buffer, looking like garbage on the end of the string, and the size returned by read will be larger.

    In addition, if the pipe is getting full, a write might not write all the data you asked it to -- it might write only as much as can fit for now, and you'll have to write the rest later.

    so ALWAYS check the return values of your read and write calls and be prepared to deal with getting less than (or more for read) than you expect.

    0 讨论(0)
提交回复
热议问题