Does the argument list pass the string quotes to exec command in C?

蹲街弑〆低调 提交于 2020-01-15 06:31:20

问题


I am using execvp for execing a new process for the command grep -l night *. Here is my code:

char * argument[5];
char keyword[] = "night";

argument[0] = (char *) malloc (sizeof(char)*25);
argument[1] = (char *) malloc (sizeof(char)*25);
argument[2] = (char *) malloc (sizeof(char)*25);
argument[3] = (char *) malloc (sizeof(char)*25);
argument[4] = (char *) malloc (sizeof(char)*25);

argument[0] = "grep";
argument[1] = "-l";
strcpy(argument[2],keyword);
argument[3] = "*";
argument[4] = NULL;

execvp ("grep", argument);

But I am getting the output from this program as "grep: *: No such file or directory" which is incorrect as executing the same command from the shell results in the list of files which contain the text "night". I do suspect that the * in the command list is being sent as a string with quotes to exec. Is my assumption correct? If so how can I rectify this problem? Any help would be highly appreciated.


回答1:


Grep does not understand the "*" argument. Usually the shell expands such arguments (it's called globbing). Of course, since exec functions don't start a shell, you don't get that functionality.

You can:

  • Use functions which do start a shell (system(3), popen(3))
  • Use glob(3), essentially doing the shells job

EDIT

You could probably write it as this (untested):

glob_t globbuf;
globbuf.gl_offs = 3;

/* Globbing magic. */
glob("*", GLOB_DOOFFS, NULL, &globbuf);

/* That's what the 3 was for. */
globbuf.gl_pathv[0] = "grep";
globbuf.gl_pathv[1] = "-l";
globbuf.gl_pathv[2] = "night";

/* Conveniently, the list is NULL-terminated. */
execvp("grep", globbuf.gl_pathv);


来源:https://stackoverflow.com/questions/9625225/does-the-argument-list-pass-the-string-quotes-to-exec-command-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!