【问题标题】:Implementation of Execv() instead of execvp()执行 Execv() 而不是 execvp()
【发布时间】: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()

标签: c linux shell exec


【解决方案1】:

execvp 在 PATH 环境变量的目录列表中搜索命令。

如果您想复制 execvp 的功能,getenv("PATH"),将字符串拆分为各个目录(以冒号分隔的字符串),然后搜索列表中的每个目录,直到找到您的可执行文件和 execv () 它。

如果您的可执行文件名已经是一个以 / 字符开头的绝对路径,当然可以跳过搜索部分;在这种情况下 execvp 等价于 execv。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-05
    • 2019-09-08
    • 2016-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多