如何将execv用于其位置未知的命令?(How to use execv for commands whose location is not known?)

编程入门 行业动态 更新时间:2024-10-27 14:19:12
如何将execv用于其位置未知的命令?(How to use execv for commands whose location is not known?)

假设我想生成一个进程并运行execv来执行像ls这样的命令然后我就是这样做的:

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

现在的问题是,我在这里硬编码了ls命令所在的位置( /usr/bin/ls )。 现在假设我不知道特定命令在哪里并且想要执行它然后我该怎么做呢? 我知道在常规shell中查找PATH变量以实现相同,但是在使用execv的C程序的情况下如何实现它?

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?

最满意答案

使用execvp(3)代替execv(3) 。 execvp和execlp分别与execv和execl完全相同,只是它们在$PATH环境变量中搜索可执行文件(有关完整详细信息,请参见手册页)。

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

更多推荐

本文发布于:2023-08-07 16:00:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1464729.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何将   命令   位置   location   execv

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!