Why the environment variable is not set after using setenv ()

I wrote a C program on Linux to set the values โ€‹โ€‹of environment variables using setenv , but after execution, when I run set or export , the environment variable itself does not seem to be set. What for?

Here is the code snippet:

 int main() { char *mallocPtr, *callocPtr, *reallocPtr, *memalignPtr, *vallocPtr; struct sigaction sa; sa.sa_handler=SIGSEGV_handler; sigaction(SIGSEGV, &sa, NULL); if(setenv("ENV1", "3", 1) == 0) printf("ENV1 set to 3\n"); else fprintf(stderr, "setenv failed on ENV1"); 
+6
source share
3 answers

Environment variables are set in the context of your program.

When your program exits, you will be returned to the context where your program was launched from.

+14
source

The C library treats environment variables as global parameters that you can read using getenv and configure using setenv / putenv , and which inherit the calls to the exec family, but this is a convenient fiction. As for the kernel, environment variables are the second set of arguments to main . This becomes clear if you look at the actual execve system call underlying the exec family. This is his prototype C:

 int execve(const char *filename, char *const argv[], char *const envp[]); ^^^^^^^^^^^^^^^^^^ 

See this third argument? This is the only way for process A to set the environment variables of process B. 1 Therefore, the only time process A can set the environment variables of process B when process A starts process B through fork and execve .

Your program is launched by the shell, so the shell must set its copy of the environment variables, but there is no way to return it back to the shell - just as there is no way for the C function to change the values โ€‹โ€‹of its arguments in its caller.

1 Do not lift ptrace .

+3
source

In fact, each process has its own envp char array. The main function has the following signature:

 int main(int argc, char *argv[], char *envp[]) 

Normally envp parent's envp inherit the child down the parent-child hierarchy. It is in no way passed up in the parent-child hierarchy.

+1
source

Source: https://habr.com/ru/post/894535/


All Articles