Handling arguments array of execvp?

此生再无相见时 提交于 2019-12-04 22:49:32

问题


When I call execvp, for example execvp(echo, b) where b is an array of arguments for the command a, will changing this array later affect the execvp call made previously? When I try calling execp(echo, b), it ends up printing out (null) instead of the content inside of b. Can anyone point out why and what I have to do to pass the arguments correctly?


回答1:


After you call exec() or one if its relatives, your original program doesn't exist anymore. That means nothing in that program can affect anything after the exec() call, since it never runs. Maybe you're not building your arguments array correctly? Here's a quick working example of execvp():

#include <unistd.h>

int main(void)
{
  char *execArgs[] = { "echo", "Hello, World!", NULL };
  execvp("echo", execArgs);

  return 0;
}

From the execvp() man page:

The execv(), execvp(), and execvpe() functions provide an array of pointers to null-terminated strings that represent the argument list available to the new program. The first argument, by convention, should point to the filename associated with the file being executed. The array of pointers must be terminated by a NULL pointer.

A common mistake is to skip the part about "The first argument, by convention, should point to the filename associated with the file being executed." That's the part that makes sure echo gets "echo" as argv[0], which presumably it depends on.




回答2:


Remember, that after exec call your program is exchanged by a new one. It's not executing anymore, so any code in the same process after exec call is, in fact, unreachable.

Are you sure that b array is terminated with NULL? The last element must be NULL for exec to work correctly. Also, remember to set your first parameter to "echo" as well (it's argv[0]).

Try

execlp("echo", "echo", "something", NULL);

Btw, execlp is a bit more comfortable to use, you can pass as many parameters as you wish.



来源:https://stackoverflow.com/questions/8827939/handling-arguments-array-of-execvp

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