我想学习如何实现execv()而不是execvp()
我有带有execvp()的代码,我试图将它转换成execv(),但我失败了,因为我找不到命令的路径。哪个命令获取我认为的文件的路径,但是我如何将其实现到execv()
我想转换这段代码:
if ((pid = fork()) < 0) { /* fork a child process */
printf("*** ERROR: forking child process failed\n");
exit(1);
}
else if (pid == 0) { /* for the child process: */
printf("hophop");
if (execv("/usr/bin/ls"+*args[0], args) < 0) { /* execute the command */
printf("*** ERROR: exec failed\n");
exit(1);
}
}
else { /* for the parent: */
while (wait(&status) != pid) /* wait for completion */
;
}
/** the steps are:
(1) fork a child process using fork()
(2) the child process will invoke execvp()
(3) if background == 0, the parent will wait,
otherwise it will invoke the setup() function again. */发布于 2014-12-04 08:26:14
execvp在PATH环境变量的目录列表中搜索该命令。
如果要复制execvp、getenv("PATH")的功能,请将字符串拆分为单独的目录(以冒号分隔的字符串),然后在列表中搜索每个目录,直到找到可执行文件,并使用execv()将其删除。
如果您的可执行文件名已经是以/字符开头的绝对路径,那么当然可以跳过搜索部分;在这种情况下,execvp等同于execv。
https://stackoverflow.com/questions/27283832
复制相似问题