I would like to see if the environment variable I have passed in the execve() function has really been passed, so I made this code (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);
}
But, when I execute the binary issued by Main.c, I get this output:
PATH :(null)
whereas I want to see
PATH: bin
Do you have any explanation?
Environment strings must be in the format of VARIABLE_NAME=value of the variable
.
Your PATH
variable (the C variable, not the environment variable) should be a string with the contents PATH=bin
.
Also, you need to end it with an extra null (along with the null that comes with the last string, of course) to indicate that there are no more strings in the environment.
From the execve(2)
manpage (emphasis mine):
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)).
and from the environ(7)
manpage:
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''.
Your string buffer PATH is not large enough for the string you're trying to put into it.
The environment string needs to be "PATH=bin"
, not just "bin"
.
As the other answer indicates, you need to end your list of environment strings with a null pointer, i.e. char *newenviron[] = {PATH, 0};
.
You might try examining the environment structure that's passed to your program before modifying it, to see the necessary format. Here's an example of how to do this: http://nibot-lab.livejournal.com/115837.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With