小编Ken*_*eno的帖子

什么时候需要execle而不是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;
}
Run Code Online (Sandbox Code Playgroud)

script.sh存在

#!/bin/bash

case $DEBUG in
true)
    echo "Debug mode on"
    ;;
*)
    echo "Debug mode off"
    ;;
esac
Run Code Online (Sandbox Code Playgroud)

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

DEBUG=true ./foo

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

extern char **environ;
...
execle(path, …
Run Code Online (Sandbox Code Playgroud)

c exec environment-variables

2
推荐指数
1
解决办法
83
查看次数

标签 统计

c ×1

environment-variables ×1

exec ×1