0

编辑:** 已回答问题:请参阅 PaulMckenzie 和 Rishikesh Raje 的评论

此函数的目的是使用管道在参数上调用 grep filepattern但我在程序中遇到了堆栈粉碎的问题。它运行并直接运行到函数的末尾,但随后抱怨堆栈粉碎。这是我的代码:

void count_pattern(char *file, char *pattern) {
  int bytes_read;
  int nbytes = 20000;
  char *read_string;
  char grep_str[] = "";
  FILE *grep_pipe;
  FILE *wc_pipe;

  strcat(grep_str, "grep ");
  strcat(grep_str, pattern);
  strcat(grep_str, " ");
  strcat(grep_str, file);
  strcat(grep_str, "\0");

  grep_pipe = popen (grep_str, "r");
  wc_pipe = popen ("wc -l", "w");

  /* Pipe Error Checking*/
  if ((!grep_pipe) || (!wc_pipe))
  {
      fprintf (stderr,"One or both pipes failed.\n");
  }
  /* Read from grep_pipe until EOF? */
  read_string = (char *) malloc (nbytes + 1);
  bytes_read = getdelim (&read_string, &nbytes, -1, grep_pipe);


  /* Close grep_pipe */
  if (pclose (grep_pipe) != 0)
  {
      fprintf (stderr, "Could not run 'grep'.\n");
  }

  /* Send output of 'grep' to 'wc' */
  fprintf (wc_pipe, "%s", read_string);

  /* Close wc_pipe */
  if (pclose (wc_pipe) != 0)
  {
      fprintf (stderr, "Could not run 'wc'.\n");
  }

printf("%s\n\n",grep_str); /* migrating bug-check print statement */
}

使用参数 file="somefile" pattern="somepattern" 在 main 中运行它会在最后输出正确的数量somepatterns以及somefile典型的迁移错误检查打印语句,之后它会因堆栈粉碎而终止。

在阅读了堆栈粉碎后,似乎管道的某个末端过度扩展了对非法空间的读取或写入。但是,我不确定在哪里或为什么会发生这种情况,因为在函数结束之前一切似乎都运行良好。此处有关堆栈粉碎的其他帖子暗示,当堆栈粉碎可能发生时,是编译器将金丝雀扔到代码中表示失败。问题不在于main两者。任何人都可以说明情况吗?

参考: http ://crasseux.com/books/ctutorial/Programming-with-pipes.html

是此代码主要基于的地方。

4

1 回答 1

1

问题不在于管道。该问题与字符串与空字符串变量 grep_str 的连接有关,该变量显然无法在其中容纳更多字符串。感谢评论中的保罗和瑞诗凯诗

于 2018-09-27T04:21:28.520 回答