execv具有从第二个元素开始的参数
我正在制作一个可以将另一个程序作为参数并运行的程序。
我正在使用execv()
来运行第二个程序,但是我如何使用argv []
(来自主程序,是char*<< /code>)作为
execv()
的参数?
argv []
的第一个元素是主程序的名称,因此我需要从下一个程序名称所在的第二个元素开始。
我认为可能有不同的解决方案,例如:
- tell
execv()
从第二个参数开始 - 复制
argv []
(第一个元素除外)的内容到另一个元素数组并将其 - 与指针一起使用,所以也许我可以指向第二个元素,然后从那里开始,
这是最好的方法? 我可以得到如何做的例子吗?
I am making a program that can take another program as an argument and run it.
I am using execv()
to run the second program, but how can I use argv[]
(that comes from the main program, is a char*
) as arguments for execv()
?
The first element of argv[]
is the name of the main program, so I need to start at the second element where the name of the next program is located.
I am thinking there might be different solutions, for example:
- Tell
execv()
to start from the second argument - copy the content of
argv[]
(except first element) to another array and use that - Something with pointers so maybe I can point to the second element and start there
What is the best way to do this?
And can I get an example of how to do it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,argv实际上是一个指向指针数组的指针。更正确的定义方法是
char **argv
。将其定义为
*argv[]
只是一个语法糖。所以你的第三个猜测是最好的一个:你还可以使用互换函数参数
char **argv
与char *argv[]
并且你不会看到差异。但是像这样的代码:
会给你一个错误 - 类型转换无效。这是因为在堆栈上定义数组需要在编译期间知道数组的大小。但是将数组定义为函数参数 - 则不然,在这种情况下,编译器假定堆栈操作是在调用函数中完成的。
First of all, the
argv
is actually a pointer to array of pointers. The more correct way to define it would bechar **argv
.Defining it as
*argv[]
is just a syntactic sugar. So your third guess is a best one:You can also play with interchanging function arguments
char **argv
vschar *argv[]
and you wont see a difference.But code like:
will give you an error - of invalid type conversion. That is due to a fact that defining an array on a stack requires to know the size of array during the compilation. But defining array as a function parameter - does not, the compiler in that case presumes that the stack manipulation is done in the caller function.