c - execvp(grep) 后失去控制

标签 c shell grep execvp

我正在尝试编写一个小程序来通过 execvp 运行 grep。这与我遇到的问题基本相同here ,但在这种情况下,只有当我运行 grep (而不是 echo、ls、emacs 等,它们都工作正常)并且我更改了不正确的 wait() (我相信)时,才会发生这种情况。我还尝试过在我想要查找的文本上使用引号

我的代码:

int main(void) {

  int i;
  char inputprogram[50];
  char vars[50] = "a search.txt";
  printf("input grep\n");
  fflush(stdout);
  fgets(inputprogram,50,stdin);
  for(i = 0; i < 50; i++){
            if(inputprogram [i] == '\n' ){
                inputprogram[i] = 0;
            }
        }
  char *arg [] = {inputprogram, vars , NULL};
  printf(">%s<\n", arg[1]);
  printf(">%s<\n", arg[0]);

  int status = 0;
  pid_t child;

  (child = fork());
  if(child == 0){
    printf("execute\n");
    execvp(inputprogram,  arg);
    exit(1);
  }
  else{
    printf("parent waiting...\n");
    wait(&status);
  }
  return EXIT_SUCCESS;
}

搜索.txt:

a
b
c
abc

输入/输出(# 位于我输入的行前面,但不是输入的一部分):

shell> # ./work
input grep
# grep
>a search.txt<
>grep<
parent waiting...
execute
# a;dlghasdf
# go back
# :(

最佳答案

函数 execvp 期望每个参数作为传入数组中的单独参数。您将“vars”作为单个参数传递,其中包含空格。 Grep 正在等待来自标准输入(此处为控制台)的输入,并正在搜索包含“a search.txt”的行。以下程序将执行您所期望的操作。

#include "unistd.h"
int main(void) 
{
  char * executable = "grep";
  char *arg[] = { executable, "a","search.txt", NULL };
  execvp(executable, arg);
  return 0;
}

通过将搜索到的字符串作为其自己的参数传递,grep 将列表中的下一个参数视为要搜索的文件。

以下是该程序为我所做的事情:

ericu@eric-phenom-linux:~$ gcc -o execgrep /home/ericu/execgrep.c 
ericu@eric-phenom-linux:~$ ./execgrep 
a
abc
ericu@eric-phenom-linux:~$ cat search.txt 
c
b
a
abc
ericu@eric-phenom-linux:~$ 

修改示例程序以反射(reflect)您当前正在执行的操作

#include "unistd.h"
int main(void) 
{
   char * executable = "grep";
   char *arg[] = { executable, "a search.txt", NULL };
   execvp(executable, arg);
   return 0;
}

导致程序期望来自标准输入的输入。

ericu@eric-phenom-linux:~$ echo -e "Review the man page from proper usage of execvp.a search.txt\nThis line does not show up in the output" | ./execgrep 
Review the man page from proper usage of execvp.a search.txt
ericu@eric-phenom-linux:~$ 

关于c - execvp(grep) 后失去控制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15298101/

相关文章:

ios - Apple 数学库与 C 中的其他数学库

c - 如何输入n行每行m个字符的字符串,其中可能包含空格作为字符?

c++ - 链接器如何解析汇编代码中的符号

bash - "declare +x"与 "declare -x"是什么意思?

xml - grep 多个字符串并在变量中存储/打印下一行值

xml - Grep 仅一行,然后删除

c - 如何以编程方式确定 C 中 int 数据的最大和最小限制?

bash - shell 中文件的一列中的唯一单词数

perl - Bash/shell 错误运行 perl -e 'use [module]' : Can't find string terminator "' "anywhere before EOF at -e line 1

linux - Grep 来自多个文件的值