1

Which exec system call family members can be used without knowing full path of the given command. For example when

"/bin/ls -t" "/bin/cat -n" "/usr/bin/tr /a-z/ /A-Z/" 

inputs given from the commandline I can properly use execv(arg[0],args) like this

(arg[0] -> full path of the command and args -> arguments of the command)  

but when I have "ls /sbin" "wc -w" "cat" inputs I can not use execv.

user3117189
  • 69
  • 3
  • 9

2 Answers2

4

By looking at the function names I'm assuming that this is not shell scripting but instead normal C on POSIX.

In C you may use the execlp() or execvp() functions. Whele the extra 'p' means that PATH environment variable is used for finding the given executable.

For example:

    execlp("ls", "ls", "-t");

instead of:

    execl("/bin/ls", "ls", "-t");
0

You can do that with all "family members", provided the executables are inside your PATH environment variable. That variable can hold a colon separated list of paths that are searched when an executable is to be executed. So all you have to do is setup that variable correctly. Typical setups include these paths

  • ~/bin (the current users bin folder)
  • . (the current directory)
  • /bin
  • /usr/bin
  • /usr/local/bin

Note that you have to take care which user account actually executes the command in question - this can be changed in a dynamic manner. In that case it might be a different PATH variable, not that inside the environment of the calling scope. But usually the environment is completely handed over to a sub process. This again means that you can first set and "export" the PATH variable, then do you call and it is inherited by the called scope.

If, whyever, you cannot use that environment variable, then you somehow will have to emulate that behaviour: since the location of some executable cannot be magically guessed by an exec call or a shell, either the location must be known or it has to be searched. So you'd have to implement such a search algorithm, you might do that inside some minimalistic shell (typically called a "wrapper") which you use to actually execute the final command. So you call the wrapper, hand over the command to be executed as argument, and the wrapper known in what places to search for the command. But then again this is exactly what the PATH variable is there for.

Another option would be to rely on the PATH variable and a shells algorithm to search it for the executable required, but do that in a manual way. This is what the whereis and the which commands are there for: take a look at their man pages, they both allow to search the PATH variable and return matches. So you can first query the absolute location of your desired executable and then call it with that absolute path.

arkascha
  • 41,620
  • 7
  • 58
  • 90