[英]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.
我可以知道如何解决这个问题吗? 我可以让子进程一直等到它真正从管道中读取数据吗?
我编辑了程序。 并且它可以读取所有数据。 但是,该程序只是停止。 它无法继续处理。 我认为它停止在子进程中。
//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");
}
编辑:如果写入大小大于>写入数据,则效果不佳。 垃圾结束。
它确实从管道读取了数据。 您说“最多读取20个字节”,它确实做到了(请注意,它也有17个垃圾字节,并且您的父进程正在读取3字节缓冲区的末尾,试图发送它们!)。 如果希望它读取更多字节,请再次调用read()。
read
将读取最多您指定的字节数。 它读起来可能更少:这一切都取决于缓冲。 为了确保获得所需的字节数,必须在循环中使用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.