//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.
答案 0 :(得分:1)
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");
}
修改:如果写入尺寸为&gt;则效果不佳写数据。最后的垃圾。
答案 1 :(得分:0)
它确实从管道读取数据。你说&#34;读取最多20个字节&#34;,它确实(注意它也有17个垃圾字节,并且你的父进程正在读取超过3个字节的结尾缓冲区试图发送它们!)。如果您希望它读取更多字节,请再次调用read()。
答案 2 :(得分:0)
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);