从C中的管道跳过值读取整数
我想了解C语言中管道的工作原理。 我的父进程生成从1到10的整数,并将它们写入管道中。我的子进程必须读取管道并将值打印到屏幕上。父亲等待孩子终止并退出。简单,对吗?这是我的密码:从C中的管道跳过值读取整数,c,pipe,C,Pipe,我想了解C语言中管道的工作原理。 我的父进程生成从1到10的整数,并将它们写入管道中。我的子进程必须读取管道并将值打印到屏幕上。父亲等待孩子终止并退出。简单,对吗?这是我的密码: #include <stdio.h> #include <stdlib.h> #include <signal.h> #include <sys/types.h> #include <errno.h> #include <string.h> #d
#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);
}
}
不管我在管道中写入的整数序列是什么,我的read()都会跳过每2个值。我尝试在将值写入管道时休眠(1),但结果相同。我错过了什么,但我不明白。
发生了什么事?读取1并打印,然后在
状态下,读取2并丢弃它。同样,您将丢弃每个偶数值。在while条件下读取10并返回非零,因此循环继续,然后在if read中返回0,而不是-1,因此打印10。将循环写为while((rv=read(…)!=0){…}
您的do while
循环条件也执行read
,但您不使用该值。相反,当循环开始时,您只需再次读取,从而跳过每2个值。使用不同的条件,或者使用您读取的值
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