我正在用C编程编写一个正在运行的Shell脚本。我已经了解了exec函数,尽管了解不多,但是我已经阅读了一个示例,其中像这样使用execvp


  execvp(* argv,argv);
  
  / *此处argv是一个char指针数组,其中包含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工作的简化和抽象视图。您必须仔细阅读源代码以更好地了解内部工作原理

关于c - execvp函数不带路径工作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7735533/

10-13 05:43