How to use execv for commands whose location is unknown?

Say I want to start a process and run execv to execute a command like ls , then I will do this:

 char * const parm[] = { "/usr/bin/ls","-l" , NULL }; if ((pid = vfork()) == -1) perror("fork error"); else if (pid == 0) { execv("/usr/bin/ls", parm); } 

Now the question arises that here I am hard-coded, where the ls ( /usr/bin/ls ) is present. Now suppose that I don’t know where any particular command is present and wants to execute it, then how can I do it? I know that in a normal shell, the PATH variable is checked to achieve the same, but in the case of a C program using execv , how can I achieve it?

+4
source share
1 answer

Use execvp(3) instead of execv(3) . execvp and execlp work exactly the same as execv and execl respectively, except that they look for the $PATH environment variable for the executable (see the man page for more details).

+7
source

All Articles