假设我想生成一个进程并运行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).
更多推荐
发布评论