管道不可读 c

发布于 2024-10-03 01:37:58 字数 485 浏览 1 评论 0原文

我正在编写一些涉及管道的代码。这个想法是,我应该有一个无限循环的进程,并将数据添加到管道中(我通过读取文件并在 while 循环中逐行进行测试)。

如果我将另一个进程(读取管道的进程)设置为睡眠状态,以便读取整个文件,我就没有问题并在输出中获取所有文件。一旦我取消睡眠(所以现在两个进程同时启动,第二个进程从管道中读取信息),我的代码就会直接进入下面代码的 else 块,我永远不会看到任何实际输出。我做错了什么?

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);
  }
} 

谢谢

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 comes), 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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

停顿的约定 2024-10-10 01:37:58

两件事:

  1. 你是否使 pipeline[0] 成为非阻塞的?它会类似于 int nbio=1; ioctl(pipe[0], FIONBIO, &nbio);
  2. 你检查错误是错误的。
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");
}

可能 errno 第一次是 EWOULDBLOCK,然后在成功读取时不会更新,所以它看起来又像 EWOULDBLOCK。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文