2015-05-02 45 views
0

我试图了解管道是如何在C中工作的。 我的父进程生成从1到10的整数并将它们写入管道。我的子进程必须读取管道并将值打印到屏幕上。父亲等待孩子终止并退出。很简单,对吧?这里是我的代码:从管道跳过读取整数C中的值跳过

#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 

不管我在管写整数序列中,我阅读()跳过每第二个值。我试着睡觉(1),而将值写入管道,但结果是一样的。我错过了一些东西,但我没有得到什么。 发生了什么?

回答

1

您阅读1并打印,然后在while的条件下,您读取2并丢弃它。同样,你放弃每一个偶数值。 10个被读入while条件和返回非零值,因此该循环继续下去,那么在读,如果返回0,这是不是-1,所以你打印10写环路while((rv = read (...)) != 0) { ... }

1

do-while循环条件也执行read,但您不使用该值。相反,当循环开始时你只是再读一次,从而跳过每一个第二个值。要么使用不同的条件,要么使用您读取的值。