[英]read integers from pipe skips values in C
我试图了解管道如何在C中工作。我的父亲进程会生成1到10之间的整数并将它们写入管道中。 我的子进程必须读取管道并将其打印到屏幕上。 父亲等待孩子解雇并退出。 容易吧? 这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/types.h>
#include <errno.h>
#include <string.h>
#define WRITE 1
#define READ 0
#define N 10
int main(void)
{
pid_t pid;
int B0[2];
int num, status, i;
pipe(B0);
pid = fork();
if (pid > 0){
/*P0*/
close(B0[READ]);
for (i=1; i<=N; i++){
num = i;
write(B0[WRITE],&num,sizeof(num));
printf("P0: written %d\n", num);
}
close(B0[WRITE]);
wait(&status);
exit(EXIT_SUCCESS);
}
else if (pid == 0){
/*P1*/
close(B0[WRITE]);
do{
if (read(B0[READ],&num,sizeof(num)) != -1)
printf("P1: read %d from pipe B0\n", num);
else
printf("read: %s\n", strerror(errno));
} while(read(B0[READ],&num,sizeof(num)) != 0);
exit(EXIT_SUCCESS);
}
}
我不明白为什么输出以下信息:
P0: written 1
P0: written 2
P0: written 3
P0: written 4
P0: written 5
P0: written 6
P0: written 7
P0: written 8
P0: written 9
P0: written 10
P1: read 1 from pipe B0
P1: read 3 from pipe B0
P1: read 5 from pipe B0
P1: read 7 from pipe B0
P1: read 9 from pipe B0
P1: read 10 from pipe B0
无论我在管道中写入的整数序列如何,我的read()都会跳过每个第二个值。 在将值写入管道时,我尝试了sleep(1),但结果是相同的。 我缺少了一些东西,但是我什么也没得到。 发生了什么?
读取1并打印,然后在while
条件下读取2并丢弃它。 同样,您丢弃每个偶数值。 在while条件中读取10并返回非零值,因此循环继续进行,然后在if read返回0而不是-1时,则打印10。将循环编写为while( ( rv = read (... )) != 0 ) { ... }
您的do-while
循环条件也执行read
,但是您不使用该值。 相反,您只需在循环开始时再次读取,从而跳过每个第二个值。 可以使用其他条件,也可以使用已读取的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.