Handling an array of execvp arguments?

When I call execvp , for example execvp(echo, b) , where b is an array of arguments for command a, will changing this array later affect the execvp call made earlier? When I try to call execp (echo, b), it finishes printing (null) instead of the contents inside b. Can someone please indicate why and what I need to do to pass arguments correctly?

+6
source share
2 answers

After calling exec() or one, if its relatives, your original program no longer exists. This means that nothing in this program can affect anything after calling exec() , since it never starts. Maybe you are not building your array of arguments correctly? Here is a quick working example of execvp() :

 #include <unistd.h> int main(void) { char *execArgs[] = { "echo", "Hello, World!", NULL }; execvp("echo", execArgs); return 0; } 

On the execvp() page:

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

A common mistake is to skip the part "The first argument, by convention, should point to the file name associated with the executable file." That the part that provides echo receives an "echo" like argv[0] , which apparently depends on.

+12
source

Remember that after exec call your program is exchanged for a new one. It is no longer executing, so any code in the same process after calling exec is essentially inaccessible.

Are you sure array b is terminated with NULL? The last element must be NULL for exec to work correctly. Also, be sure to also set your first parameter to echo (this is argv [0]).

Try

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

Btw, execlp little more convenient to use, you can pass as many parameters as you like.

0
source

Source: https://habr.com/ru/post/905773/


All Articles