什么时候需要execle而不是execl?

When is execle needed instead of execl?

考虑这个简单的 C 程序

#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>

int main()
{
    if (fork() == 0)
    {
        execl("script.sh", "script.sh", NULL);
        exit(EXIT_FAILURE);
    }
    int status;
    wait(&status);
    if (WIFEXITED(status) && WEXITSTATUS(status) == EXIT_SUCCESS)
    {
        return 0;
    }
    return -1;
}

其中 script.sh

#!/bin/bash

case $DEBUG in
true)
    echo "Debug mode on"
    ;;
*)
    echo "Debug mode off"
    ;;
esac

如果我用 gcc -o foo main.c 编译 C 程序并用

调用它

DEBUG=true ./foo

然后输出是Debug mode on,所以脚本实际上得到了我传递给程序的环境变量foo,即使我没有使用execle。那么在哪种情况下有必要使用 execle (除了想要直接在源代码中指定环境变量之外)?我说的是人们在做类似

extern char **environ;
...
execle(path, path, NULL, environ)

这样做的目的是什么?

当您不希望环境被继承时(您希望可执行文件从空环境或您专门为其设置的环境开始)。