Say I want to spawn a process and run execv to execute a command like ls then this is how i do it:
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 is that here I have hard coded where the ls command is present (/usr/bin/ls). Now suppose I do not know where a particular command is present and want to execute it then how do I go about it? I know in a regular shell the PATH variable is looked up to achieve the same, but in case of a C program using execv how do I achieve it?
Use
execvp(3)instead ofexecv(3).execvpandexeclpwork exactly likeexecvandexeclrespectively, except they search the$PATHenvironment variable for an executable (see the man page for full details).