How to change another process’ environment variable in Linux?

Each process has its environment variables in Linux. But is it possible to change another process’ environment variable from another process in Linux? If it is possible to do so, how to do it?

There is a trick which can work for some scenarios. First, find out the process ID, then start gdb and attach to the process. After gdb has attached to the process, call the putenv() with the environment variable name and value.

$ sudo gdb -p <process ID>
(gdb) call putenv ("MYVAR=myvalue")
(gdb) detach

Let’s test it with an C++ program as follows.

#include <cstdlib>

#include <iostream>
#include <chrono>
#include <thread>

int main()
{
   while (true) {
      if (const char* myvar = std::getenv("MYVAR"))
         std::cout << "MYVAR is: " << myvar << '\n';
      else
         std::cout << "MYVAR is not set\n";
      std::this_thread::sleep_for(std::chrono::seconds(1));
   }
}

Build and run it

$ g++ --std=c++11 getenv.cpp -o /tmp/getenv
$ /tmp/getenv 
MYVAR is not set
MYVAR is not set
MYVAR is not set
MYVAR is not set
...

Now, we can find the process ID of getenv by

$ pidof getenv
52824

Then, we can attach to the process by

$ sudo gdb -p 52824
GNU gdb (Ubuntu 9.1-0ubuntu1) 9.1
...
Attaching to process 52824
...
__GI___clock_nanosleep (clock_id=clock_id@entry=0, flags=flags@entry=0, req=<optimized out>, rem=<optimized out>)
    at ../sysdeps/unix/sysv/linux/clock_nanosleep.c:79
79  ../sysdeps/unix/sysv/linux/clock_nanosleep.c: Permission denied.
(gdb) 

The getenv program stops there.

In the gdb console, let’s run

(gdb) call putenv("MYVAR=myvalue")
$1 = 0
(gdb) detach
Detaching from program: /tmp/getenv, process 52824
[Inferior 1 (process 52824) detached]
(gdb) 

Then the getenv program resumes to execute and starts to print out the MYVAR new value

..
MYVAR is not set
MYVAR is not set
MYVAR is: myvalue
MYVAR is: myvalue
MYVAR is: myvalue
...

The environment of the getenv process has been updated!

One last note, the programs may cache the environment values by itself or the libraries it uses. Under such cases, this trick will not work.