开发者

pipe not readable c

I'm working on some code involving pipes. The idea is that I'm supposed to have a process looping indefinitely and add data to the pipe as it comes (I'm testing this by reading a file, and going line by line in a while loop).

If I set the other process (the one that reads the pipe) to sleep so the entire file is read I have no problems and get all the file in the output. As soon as I remove the sleep (so now the 2 processes start simultaneously with the 2nd process reading the information off the pipe as it come开发者_StackOverflows), my code goes straight to the else block of my code below and I never see any actual output. What am I doing wrong?

close(pipe[1]);  
sleep(5);

while (1) {

  nbytes = read(pipe[0], buffer, 200);    

  if(errno != EWOULDBLOCK) {      
    printf("%s", buffer);     
  }

  else {
    printf("I am not blocked here\n");
    sleep(1);
  }
} 

Thanks


Two things:

  1. did you make pipe[0] non-blocking? It'll be something like int nbio=1; ioctl(pipe[0], FIONBIO, &nbio);
  2. you're checking for error wrong.
if(nbytes > 0) {
    /* you may need to null-terminate the input buffer prior to display */
    buffer[nbytes] = '\0';
    printf("%s", buffer);
}
else if(errno == EWOULDBLOCK) {
    printf("I am not blocked here\n");
    sleep(1);
}
else {
    printf("some other error occurred - if nbytes == 0, then it's EOF.\n");
}

probably errno is EWOULDBLOCK the first time through, and then doesn't get updated on successful read, so it looks like EWOULDBLOCK again.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜