找不到传递给 execve 函数的环境

Can't find the env passed into execve function

我想看看我在execve()函数中传递的环境变量是否真的传递了,所以我做了这段代码(Main.c) :

int main(){

    char PATH[4];
    strcpy(PATH, "bin");
    char * newargv[] = {"./get","", (char*)0};
    char * newenviron[] = {PATH};
    execve("./get", newargv, newenviron);
    perror("execve");
    return 0;
}

(get.c):

int main()
{
    const char* s = getenv("PATH");
    printf("PATH :%s\n",s);

}

但是,当我执行 Main.c 发出的二进制文件时,我得到了这个输出:

PATH :(null)

而我想看

PATH: bin

你有什么解释吗?

  1. 您的字符串缓冲区 PATH 不够大,无法容纳您尝试放入其中的字符串。

  2. 环境字符串需要 "PATH=bin",而不仅仅是 "bin"

  3. 如其他答案所示,您需要使用空指针结束环境字符串列表,即 char *newenviron[] = {PATH, 0};.

您可以尝试在修改之前检查传递给程序的环境结构,以查看必要的格式。以下是如何执行此操作的示例:http://nibot-lab.livejournal.com/115837.html

环境字符串必须采用 VARIABLE_NAME=value of the variable.

格式

您的 PATH 变量(C 变量,而不是环境变量)应该是一个包含内容 PATH=bin.

的字符串

此外,您需要用一个额外的空值(当然还有最后一个字符串附带的空值)来结束它,以指示环境中没有更多的字符串。

来自 execve(2) 联机帮助页(强调我的):

The argument envp is also a pointer to a null-terminated array of character pointers to null-terminated strings. A pointer to this array is normally stored in the global variable environ. These strings pass information to the new process that is not directly an argument to the command (see environ(7)).

并来自 environ(7) 联机帮助页:

An array of strings called the environment is made available by execve(2) when a process begins. By convention these strings have the form ``name=value''.