execvp函数无路径工作

时间:2011-10-12 05:14:31

标签: c shell exec

我正在用C编程编写一个正在运行的shell脚本。我已经阅读了关于exec函数的内容,虽然不太了解,但我已经阅读了一个例子,其中execvp就像这样使用

  

execvp(* argv,argv);

     

/ *这里argv是一个包含ls -l <​​/ p>之类命令的char指针数组      

的argv [0] - &GT; LS   的argv [1] - &GT; -l

     

* /

但它使用时没有给出文件名作为参数我不知道它是如何工作的。任何人都可以在execvp的描述中解释这一点,它给出了指定的文件名 非常感谢

1 个答案:

答案 0 :(得分:1)

在您实际通过的情况下 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工作的简化和抽象视图。您必须查看源代码以更好地了解内部工作原理