Eric Tang
Eric Tang

Reputation: 207

C:pipe How to write data multiple time on same pipe?

 //child process
    char buf[20];
    read(fd[0][0], buf, 20);
    printf("%s", buf);     

 //parent process
    write(fd[0][1], "12", 20);
    write(fd[0][1], "14", 20);
    write(fd[0][1], "15", 20);

 --output--
    12
    //then the program just exit. It cannot print out 14 and 15.

May I know that how can solve this problem? Can I make the child process waiting until it really read data from pipe?

I edited my program. And it can read all the data. However, the program just stop. It cannot continue to process. I think that it stop in the child process.

 //child process
    buf[6];
    int i;
    while ((i = read(fd[0][0], buf, 6)) > 0) {
         printf("%s", buf);     
    }

 //parent process
    write(fd[0][1], "12", 2);
    write(fd[0][1], "14", 2);
    write(fd[0][1], "15", 2);
    printf("done!\n");

 --output--
    121415done
  //The program just stopped in child process.

Upvotes: 0

Views: 5432

Answers (3)

Greg Inozemtsev
Greg Inozemtsev

Reputation: 4671

read will read up to the number of bytes you specify. It could read less: it all depends on buffering. To make sure you get the number of bytes you want, you'd have to use read in a loop:

//child process
#define MAXLEN 20
int total_read = 0, n;
char buf[MAXLEN + 1];
buf[MAXLEN] = 0;
p = buf;
while (total_read < MAXLEN) {
    n = read(fd[0][0], p, MAXLEN - total_read);
    if (n < 0)
        break; //error
    if (n == 0)
        break; //end of file
    total_read += n;
    p += n;
}
printf("%s", buf);

Upvotes: 0

Morpfh
Morpfh

Reputation: 4093

static const int BUF_SIZE = 4;
char buf[BUF_SIZE];

ssize_t read_bytes;
int i;

while ((read_bytes = read(fd[0][0], buf, BUF_SIZE)) > 0) {
    printf("BUF: {\n'");

    for (i = 0; i < read_bytes; ++i) {
        if (buf[i] != '\0')
            putchar(buf[i]);
    }

    printf("'\n} : EOBUF[%d]\n", nbytes);
}

if (read_bytes < 0) {
     perror("FAIL");
}

Edit: Works bad if write size is > write data tho. Garbage at end.

Upvotes: 1

Andy Ross
Andy Ross

Reputation: 12043

It did read data from the pipe. You said "read up to 20 bytes", and it did (note that it got 17 garbage bytes too, and that your parent process was reading past the end of the 3-byte buffer trying to send them!). If you want it to read more bytes, call read() again.

Upvotes: 0

Related Questions