简体   繁体   中英

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.
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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM