简体   繁体   English

C:pipe如何在同一管道上多次写入数据?

[英]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!). 您说“最多读取20个字节”,它确实做到了(请注意,它也有17个垃圾字节,并且您的父进程正在读取3字节缓冲区的末尾,试图发送它们!)。 If you want it to read more bytes, call read() again. 如果希望它读取更多字节,请再次调用read()。

read will read up to the number of bytes you specify. read将读取最多您指定的字节数。 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: 为了确保获得所需的字节数,必须在循环中使用read

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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