Read / Write through a pipe in C

前端 未结 2 701
醉话见心
醉话见心 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.

提交回复
热议问题