Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use multiple arguments from an array to construct an execl() call in C?

Tags:

arrays

c

exec

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.

like image 699
chucknelson Avatar asked Apr 10 '10 15:04

chucknelson


2 Answers

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[]);
like image 90
Chris H Avatar answered Nov 15 '22 01:11

Chris H


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} 
like image 35
RichieHindle Avatar answered Nov 15 '22 00:11

RichieHindle