0

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

savanto
  • 4,470
  • 23
  • 40

1 Answers1

2

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 );
user3386109
  • 34,287
  • 7
  • 49
  • 68
  • 1
    And, interestingly, if `argv[1]` is NULL (because no argument was passed), the result is still correct. It would be trickier if you needed to pass more than one argument; at that point, `execv()` becomes the correct function. Actually, I'd argue `execv()` is more often useful than `execl()`, but `execl()` is not useless for a fixed list of arguments. – Jonathan Leffler Jun 04 '14 at 23:26