Issue
void main(int argc,char *argv[])
{
for (int i = 0; i < argc; i++)
{
printf("%s ", argv[i]);
}
}
when I use command ./test 1 2 3
in terminal to execute this program, I got result ./test 1 2 3
,but when I use function execl("/usr/src/test", "1", "2", "3", NULL)
in another program I got result
1 2 3
,why?
Solution
The syntax of execl()
is:
int execl(const char *path, const char *arg0, ..., /*, (char *)0, */);
So you have
path = "/usr/src/test"
arg0 = "1"
arg1 = "2"
arg3 = "3"
The argN
parameters are put into the argv
array of the new process.
You have to repeat the path as arg0
to put that into argv[0]
.
execl("/usr/src/test", "/usr/src/test", "1", "2", "3", NULL)
This isn't done automatically because argv[0]
isn't required to be the same as the program path, and there are some situations where it isn't (for instance, login shells are invoked by adding a -
prefix in argv[0]
).
Answered By - Barmar Answer Checked By - Marie Seifert (WPSolving Admin)