[英]How to execvp ls *.txt in C
I'm having issues execvping the *.txt wildcard, and reading this thread - exec() any command in C - indicates that it's difficult because of "globbing" issues. 我有问题执行* .txt通配符,并且在C中读取此线程 - exec()任何命令 - 表明由于“全局”问题很难。 Is there any easy way to get around this?
有什么简单的方法可以解决这个问题?
Here's what I'm trying to do: 这是我正在尝试做的事情:
char * array[] = {"ls", "*.txt", (char *) NULL };
execvp("ls", array);
you could use the system command: 你可以使用系统命令:
system("ls *.txt");
to let the shell do the globbing for you. 让外壳为您做这些事情。
In order to answer this question you have to understand what is going on when you type ls *.txt
in your terminal (emulator). 为了回答这个问题,您必须了解在终端(模拟器)中键入
ls *.txt
时发生了什么。 When ls *.txt
command is typed, it is being interpreted by the shell
. 键入
ls *.txt
命令时, shell
对其进行解释。 The shell
then performs directory listing and matches file names in the directory against *.txt
pattern. 然后,
shell
执行目录列表,并根据*.txt
模式将目录中的文件名匹配。 Only after all of the above is done, shell
prepares all of the file names as arguments and spawns a new process passing those file names as argv
array to execvp
call. 只有完成上述所有操作后,
shell
才会将所有文件名作为参数进行准备,并生成一个新进程,将这些文件名作为argv
数组传递给execvp
调用。
In order to assemble something like that yourself, look at the following Q/A: 为了自己组装类似的东西,请查看以下问题:
fnmatch()
to match file name with a shell-like wildcard pattern. fnmatch()
将文件名与类似Shell的通配符模式进行匹配。 vfork()
and one of the exec(3)
family of functions to run another program. vfork()
和exec(3)
函数系列之一来运行另一个程序。 Alternatively, you can use system()
function as @manu-fatto has suggested. 另外,您可以按照@ manu-fatto的建议使用
system()
函数。 But that function will do a little bit different thing — it will actually run the shell
program that will evaluate ls *.txt
statement which in turn will perform steps similar to one I have described above. 但是该函数会做一些不同的事情-它实际上将运行将评估
ls *.txt
语句的shell
程序,该程序随后将执行与我上面描述的步骤类似的步骤。 It is likely to be less efficient and it may introduce security holes (see manual page for more details, security risk are stated under NOTES section with a suggestion not to use the above function in certain cases). 它的效率可能较低,并且可能会引入安全漏洞(有关更多详细信息,请参见手册页,“ 注意”部分说明了安全风险,建议在某些情况下不要使用上述功能)。
Hope it helps. 希望能帮助到你。 Good Luck!
祝好运!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.