gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 15:19:15 26 4
gpt4 key购买 nike

我想看看我在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

你有什么解释吗?

最佳答案

环境字符串的格式必须是VARIABLE_NAME=value of the variable

您的 PATH 变量(C 变量,而不是环境变量)应该是内容为 PATH=bin 的字符串。

此外,您需要以额外的 null(当然还有最后一个字符串附带的 null)结束它,以指示环境中不再有字符串。

来自 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''.

关于找不到传递给 execve 函数的环境,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42449773/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com