开发者

How to use execv for commands whose location is not known?

开发者 https://www.devze.com 2023-04-09 12:38 出处:网络
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 };

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).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号