execvp函数在没有路径的情况下工作

execvp函数在没有路径的情况下工作,c,shell,exec,C,Shell,Exec,我正在用C编程编写一个运行的shell脚本。我读过关于exec函数的书,虽然不太了解,但我读过一个例子,其中execvp是这样使用的 execvp(*argv,argv) /*这里的argv是一个字符指针数组,包含像ls-l这样的命令 argv[0]->ls argv[1]->-l */ 但是它使用时没有给出文件名作为参数,我不知道它是如何工作的。任何人都可以解释这一点,因为在execvp的描述中,它被赋予了指定的文件名 非常感谢您的实际路过 Arg1:ls Arg2:ls-l 在确保您的参数不

我正在用C编程编写一个运行的shell脚本。我读过关于exec函数的书,虽然不太了解,但我读过一个例子,其中execvp是这样使用的

execvp(*argv,argv)

/*这里的argv是一个字符指针数组,包含像ls-l这样的命令

argv[0]->ls argv[1]->-l

*/

但是它使用时没有给出文件名作为参数,我不知道它是如何工作的。任何人都可以解释这一点,因为在execvp的描述中,它被赋予了指定的文件名
非常感谢您的实际路过 Arg1:
ls
Arg2:
ls
-l
在确保您的参数不为NULL后,将完成此检查

/* If it's an absolute or relative path name, it's easy. */
if (strchr(argv[0], '/')){
    execve(argv[0],argv,environ);
}
//In your case this would fail because argv[0] is not an absolute path.
//So now the search for argv[0] begins in the PATH
path = getenv("PATH")
//Now for each directory specified in path, it will attempt an execve call as
//For simplicity, I am calling each directoryname in PATH to be dir
execve(strcat(dir,argv[0]),argv,environ)
//If this generates an error called [ENOEXEC][1], then it's okay to continue searching in other directories, else quit searching and return the errorcode
我提供了execvp工作的简化和抽象视图。您必须通读源代码以更好地理解内部工作