0

I try to update environment but does not work .
this is my example code:

#include <iostream> 
#include <stdlib.h> 

using namespace std; 

extern char **environ ;

void printEnvs() {
        int size = sizeof(environ) ;

        for (int i=0;i<size;i++) {
                char* e = environ[i];
                cout << "Env: " << e << endl ;
        }
} 

int main(int argc, char *argv[])
{
        cout << "BEFORE UPDATE" << endl ;
        printEnvs(); 

        cout << "----------------------------------------------" << endl ;
        string k,v ;
        int r ;

        cout << "Please enter variable key: "; 
        cin >> k ;
        cout << "Please enter variable value: "; 
        cin >> v ;

        cout << k << "=" << v << endl ;

        r = setenv(k.data(),v.data(),0);
        if (r != 0) {
                cout << "[ERROR] failed to set environment" << endl ;
                exit(1);
        }
        cout << "----------------------------------------------" << endl ;
        cout << "AFTER UPDATE" << endl ;
        printEnvs() ;
        return 0;
}

and result ! :

BEFORE UPDATE
Env: SHELL=/bin/bash
Env: LSCOLORS=Gxfxcxdxdxegedabagacad
Env: SESSION_MANAGER=local/skynet-laptop:@/tmp/.ICE-unix/2181,unix/skynet-laptop:/tmp/.ICE-unix/2181
Env: WINDOWID=44040199
Env: COLORTERM=truecolor
----------------------------------------------
Please enter variable key: name
Please enter variable value: julia
name=julia
----------------------------------------------
AFTER UPDATE
Env: SHELL=/bin/bash
Env: LSCOLORS=Gxfxcxdxdxegedabagacad
Env: SESSION_MANAGER=local/skynet-laptop:@/tmp/.ICE-unix/2181,unix/skynet-laptop:/tmp/.ICE-unix/2181
Env: WINDOWID=44040199
Env: COLORTERM=truecolor

I misunderstood man setenv ?
Note: also i used putenv , still not working .

mah454
  • 1,571
  • 15
  • 38
  • 5
    The size of a pointer (like `sizeof(environ)`) is the size of the pointer itself, not what it might point to. – Some programmer dude Aug 01 '22 at 08:11
  • I also recommend you read [the `environ` manual page](https://man7.org/linux/man-pages/man7/environ.7.html). And use [`getenv`](https://man7.org/linux/man-pages/man3/getenv.3.html) to read any environment variable set with `setenv`. – Some programmer dude Aug 01 '22 at 08:12
  • `int size = sizeof(environ)` -- A first step in debugging your issue would have been for you to print the value of `size` and see if it made sense to you. Obviously you would have detected that it is not right. Then the question would have been better focused -- *"why when I use sizeof(environ), the value isn't what I expected"* – PaulMcKenzie Aug 01 '22 at 08:22
  • yes , thank you , i understood that problem . – mah454 Aug 01 '22 at 08:32

0 Answers0