Reputation: 173
I am writing a program using execl to execute my exe file which is testing and it's work very well and display the output in the Linux CLI. But I have not idea how to change the execl to execv, although I know both of the system call will give the same value. I am confused with the array argument for execv system call
This is my execl sample program
int main(void)
{
int childpid;
if((childpid = fork()) == -1 )
{
perror("can't fork");
exit(1);
}
else if(childpid == 0)
{
execl("./testing","","",(char *)0);
exit(0);
}
else
{
printf("finish");
exit(0);
}
}
can I know how to change the execl to execv. What I read from online, we must set the file path for my exe file and the argument of array . What type of argument need to set for the array in order to ask the program to execute the testing exe file ?
https://support.sas.com/documentation/onlinedoc/sasc/doc/lr2/execv.htm
Is it the link consist of the thing I want ? But what I read from it ,the command is request the list the file,not execute the file. Correct me I make any mistake
Upvotes: 10
Views: 91519
Reputation: 657
According to the man page the use of execv
is quite simple. The first argument is the path as a string to the program you want to execute. The second is an array of string that will be used as the arguments of the program you want to execute. It is the kind of array you get if you get the argv
array in your main function.
So the array you will pass as a parameter will be the array received in the main function of the program you execute with execv
.
By convention, the first argument should be the program name (the one you try to execute) but it is not mandatory (but strongly recommended since it is the behaviour a lot of programs are expecting). Each other string in the array should be an individual argument.
And of course, the array should be terminated with a NULL pointer to mark the end.
Array example: ["prog_name", "arg1", "arg2", "arg3", "arg4", NULL]
[] is your array, each string separated with a comma is a frame of your array and at the end you have the null frame.
I hope I am clear enough!
Upvotes: 9
Reputation: 709
In order to see the difference, here is a line of code executing a ls -l -R -a
with execl(3)
:
execl("/bin/ls", "ls", "-l", "-R", "-a", NULL);
with execv(3)
:
char* arr[] = {"ls", "-l", "-R", "-a", NULL};
execv("/bin/ls", arr);
The char(*)[]
sent to execv
will be passed to /bin/ls
as argv
(in int main(int argc, char **argv)
)
Upvotes: 30