I am trying to pass arguments to execl() function for ls command. But when I pass
/bin/ls -l -a
as arguments to my program, the execl() function doesn’t recognise the last two arguments. Why is that?Here is the code:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int i,childpid;
if(argc!=4)
{
printf("you didn't provide any commandline arguments!\n");
return 0;
}
childpid=fork();
if(childpid<0)
{
printf("fork() failed\n");
return 0;
}
else
if(childpid==0)
{
printf("My ID %d\n\n",getpid());
execl(argv[1],argv[2], argv[3],NULL);
printf("If you can see this message be ware that Exec() failed!\n");
}
while(wait(NULL)>0);
printf("My ID %d, Parent ID %d, CHild ID %d\n", getpid(),getppid(),childpid);
return 0;
}
I am on Ubuntu.
Regards
When running your program
/bin/lsappears to ignore the-largument because it is passed in the position reserved forargv[0], which is normally the (rather useless) program name.Specifically, the first argument to
execlis the program to run, and the remaining arguments get copied toargvvector as-is. Sinceargv[0]is expected to contain the program name and the actual arguments begin fromargv[1], you must compensate by providing the program name twice: