请问参数列表传递字符串报价在C exec命令? [英] Does the argument list pass the string quotes to exec command in C?
问题描述
我使用 execvp
为execing一个新的进程的命令的grep -l晚*
。这里是我的code:
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);
但我正在逐渐从该程序的输出为grep的:*:没有这样的文件或目录
这是不正确的,在列表中从壳的结果执行相同的命令
其中包含文本空中飞人的文件。我不怀疑 *
命令列表正在
发送与引号中的字符串 EXEC
。是我的假设是正确的?如果是的话我怎么能纠正这个问题?任何帮助将是非常美联社preciated。
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.
推荐答案
grep的不理解*的说法。通常情况下,外壳程序扩展等参数(这就是所谓的的通配的 )。当然,由于 EXEC
功能不启动一个shell,你没有得到该功能。
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.
您可以:
- 使用功能不 的启动shell(
- 使用
水珠(3)
,基本上从事贝壳工作
其中
系统(3)
,的popen(3)
)- Use functions which do start a shell (
system(3)
,popen(3)
) - Use
glob(3)
, essentially doing the shells job
您也许可以写,因为这(未经检验)
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);
这篇关于请问参数列表传递字符串报价在C exec命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!