【发布时间】:2023-03-24 13:55:01
【问题描述】:
我想学习如何实现 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. */
【问题讨论】:
-
这一行:'while (&status) != pid)' 应该是:'wait(&status);'
-
您确定
ls二进制文件位于您系统上的/usr/bin/中吗?which ls说什么? -
这一行:'if (execv("/usr/bin/ls"+*args[0], args)
-
"/usr/bin/ls"+*args[0]到底是什么意思?*args[0]可能是您的可执行文件名称中的第一个字母,您将把它的字符代码添加到字符串文字"/usr/bin/ls"的地址中,做一些指针运算,远远超过该字符串的末尾,并最终将一些非常奇怪的数据发送到execv()。