使用参数调用Unix外部命令 [英] Call Unix external commands with arguments
本文介绍了使用参数调用Unix外部命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我找到了一种不带参数(例如"ls","pwd")调用unix外部命令的方法.就像这样:
I've found a way to call unix external commands without arguments(ex. "ls", "pwd"). It goes like that:
//Child process
char cwd[1024];
getcwd(cwd, sizeof(cwd));
char *argv[] = {*args, NULL}//(ex.) {"ls", NULL}
char *env[] = {cwd, NULL};
//concat():method that connects 2 strings
char *command_source = concat("/bin/", *args);
execve(command_source, argv, env);
return 0;
我正在尝试转换此代码,以接受带有"ls -l"之类的参数的外部命令
I'm trying to convert this code in order to accept external commands with arguments like "ls -l"
推荐答案
假设您知道args
中的参数个数,并且它是argcs
:
Assuming that you know the number of arguments in args
and that it's argcs
:
...
char **argv = calloc(sizeof(char*), argcs+1);
for (int i=0; i<argcs; i++)
argv[i]=args[i];
argv[argcs]=NULL;
...
如果不是,则可以通过遍历数组搜索结尾的NULL来轻松确定argcs
.
If not, you can easily determine argcs
by iterating through the array searching for the ending NULL.
这篇关于使用参数调用Unix外部命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文