0

Im trying to erase a Linux environment variable with the unsetenv function in a c compiled program. I run the c program and the unsetenv is successful. But when I run the env command in the shell, TURN_ON_TESTING is still there. Why will it not erase?

my c program is

#include <stdlib.h>


void main()
{
char *name = "TURN_ON_TESTING";
if(unsetenv(name) == -1)
    printf("Error");





}

thx

  • Possible duplicate of [Set environment variables in C](https://stackoverflow.com/questions/3416638/set-environment-variables-in-c) – Tsyvarev Feb 08 '18 at 08:14

1 Answers1

1

Oh, but it erases. Unfortunatelly not what you want.

When you are running your binary bash is creating its 'subprocess' and copies all variables into it. Let us consider following code:

// ununsetter.cpp

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

int main()
{
char *name = "TURN_ON_TESTING";
char *val = "NEW_VALUE";

std::cout << "OLD VALUE: " << getenv(name)<<std::endl;

if(setenv(name, val, 10) == -1)
  return -1;

std::cout << "NEW VALUE: " << getenv(name)<<std::endl;

 return 0;

}

Now lets do the testing:

export TURN_ON_TESTING=OLD_VALUE;
./ununsetter
echo $TURN_ON_TESTING;

As you'll see states of TURN_ON_TESTING will look like:

OLD_VALUE  ---> before running app
OLD_VALUE  ---> while running app, but before setting it to NEW_VALUE
NEW_VALUE  ---> while running app, after setting it to NEW_VALUE
OLD_VALUE  ---> after app is finished

The problem is that those values are not the same 'objects' as first and last one.

ravenwing
  • 668
  • 3
  • 20