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/开发者_Python百科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 of execv(3)
. execvp
and execlp
work exactly like execv
and execl
respectively, except they search the $PATH
environment variable for an executable (see the man page for full details).
精彩评论