6

I have a string array in C named args[] - now how can I use this list of arguments to construct a proper call to execl()?

So if the array contains:

{"/bin/ls","ls","-a","-l"} 

...how can I eventually construct an execl() call that is:

execl("/bin/ls","ls","-a","-l",NULL);

I must be thinking about this wrong, as I can't find anything online, just talk about defining functions that can take a variable number of arguments.

1
  • I was about to ask this question and found this one :) Thanks. Commented Jul 6, 2011 at 8:18

3 Answers 3

9

Taken directly from "man execl"

The execv() and execvp() 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.

EDIT: Here are the prototypes.

int execv(const char *path, char *const argv[]);
int execvp(const char *file, char *const argv[]);
Sign up to request clarification or add additional context in comments.

1 Comment

That's what I get for having tunnel vision and just "using what I know". Thanks to both answers.
8

If you have an array that you want to pass to one of the exec* family, you should use execv rather than execl.

Your array should be terminated by a NULL pointer, which yours currently isn't:

{"/bin/ls","ls","-a","-l", NULL} 

Comments

3

First, make sure your args[] array has a NULL pointer as the last element, then call

execv(args[0], &args[1]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.