Reputation: 7
I am making a C program that lists files using execl
to execute the ls
command. If the program is called without any command line arguments, the current directory is listed and if the user specifies a file directory as a command line argument then that directory is listed.
execl("/bin/ls", "ls", NULL);
works fine for listing the current directory
execl(argv[1], "ls", NULL);
is what I'm using for the command line argument. I think this works fine code wise but I can't get the syntax right when I'm making the command line argument:
./a.out /test/ls
Upvotes: 0
Views: 2167
Reputation: 34839
Straight from the man page for execl
The initial argument for these functions is the pathname of a file which is to be executed.
So if the command you want to run is ls
, then the first argument to execl
should be "/bin/ls"
.
The second argument to execl
should also be "/bin/ls"
. This is due to the fact that the second argument to execl
is passed as argv[0]
to the program, and argv[0]
is supposed to be the path to the program.
Thus, it's only starting at the third argument to execl
that you actually start to pass real parameters to the command. So the call should look like this
execl( "/bin/ls", "/bin/ls", argv[1], NULL );
Upvotes: 2