【问题标题】:How to search a character in a stream and push back in stream using pipes如何在流中搜索字符并使用管道在流中推回
【发布时间】:2017-01-31 12:46:34
【问题描述】:

我想在流中搜索一个字符并在流中推回而不消耗任何数据。 我正在使用 fgetc,但程序在调用 fgetc 时卡住了。

下面是我的测试程序。

int main(void)
{
  int     fd[2], nbytes;
  pid_t   childpid;
  char    string[] = "Hello, world!\n";
  char    readbuffer[80];

  pipe(fd);

  if((childpid = fork()) == -1)
    {
      perror("fork");
      exit(1);
    }

  if(childpid == 0)
    {
      /* Child process closes up input side of pipe */
      close(fd[0]);

      /* Send "string" through the output side of pipe */
      write(fd[1], string, (strlen(string)+1));
      exit(0);
    }
  else
    {
      /* Parent process closes up output side of pipe */
      close(fd[1]);
      int dummy;
      fd_set set;
      struct timeval timeout;
      FD_ZERO (&set);
      FD_SET (fd[0], &set);
      timeout.tv_sec = 1;
      timeout.tv_usec = 0;
      if (select (fd[0]+1, &set, NULL, NULL, &timeout))
        {
          dummy = fgetc (stdin);
          ungetc (dummy, stdin);
          // Search for character
          if (dummy == 0x03)
               // Todo  
        }
    }

  return(0);
}

那么,程序卡在 fgetc 上的代码有什么问题。

【问题讨论】:

    标签: c pipe fork


    【解决方案1】:

    您正在尝试从stdin(这是您的终端)而不是管道来fgetc。您没有在任何地方使用管道。尝试了解您的代码实际在做什么。

    我认为您打算将管道 fd dup2 设置为 0,即标准输入 fd。这样的例子有数千个。

    如果没有 Libc 的缓冲,或者自己实现它,你就不能做你所要求的 - 一旦从管道中读取一个字节,它就是你的并且从管道中消失了。

    【讨论】:

    • 感谢您指出我使用的是来自标准输入的终端输入,而不是节省大量时间的管道。
    • 你是说函数:ungetc() 不会推回管道上的字符吗?
    • 不,我是说 ungetc 是一个 libc 函数,它适用于 FILE* 流 - actual 文件描述符之上的 libc 抽象(就像你的管道)。
    【解决方案2】:

    我认为有两个问题。一个是一旦从流中消耗了一个字节,就无法将其推回。其次,fgetc 是一个阻塞函数,它会一直等到数据可用,如果没有,你不能告诉fgetc 返回(甚至在达到超时后返回)。

    对于第一个问题,您可以用缓冲区包装相关的流,然后在整个程序中以及预取工作的地方使用该缓冲区。

    对于第二个问题,例如,请参阅 non blocking I/O 上的此(或类似)帖子(如果有帮助,请不要忘记对引用的答案进行投票)。

    【讨论】:

      猜你喜欢
      • 2013-12-09
      • 2014-07-04
      • 1970-01-01
      • 1970-01-01
      • 2023-03-26
      • 2019-05-23
      • 1970-01-01
      • 2020-05-26
      • 1970-01-01
      相关资源
      最近更新 更多