Skip to content

Instantly share code, notes, and snippets.

@coderofsalvation
Last active February 22, 2022 15:38
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save coderofsalvation/e1376e4d2b29607431df to your computer and use it in GitHub Desktop.
Save coderofsalvation/e1376e4d2b29607431df to your computer and use it in GitHub Desktop.
updates an environment variable of a running process
# updates an environment variable of a running process (needs sudo)
# example: sudo export_pid <variable=value> <pid>
export_process(){
script=/tmp/.gdb.$2
echo -e "attach $2\ncall putenv (\"$1\")\ndetach\n" > $script
gdb -q -batch -x $script &>/dev/null
rm $script
}
@blueyed
Copy link

blueyed commented Apr 25, 2016

Nice!

Simpler:

set_env_for_pid() {
  sudo gdb -q -batch -ex "attach $1" -ex "call putenv(\"$2\")" -ex 'detach' 
}

@amosbird
Copy link

amosbird commented Jun 2, 2017

hmm, I tried this with awk 'BEGIN {RS="\0"; ORS="\n"} $0' /proc/"$proc"/environ;. I cannot get the newly put env

@kakash1hatake
Copy link

If I attach gdb to the current shell and try to set env variable it remains the same(or doesn't exist):

$] sudo gdb -p $$
(gdb) call putenv("TEST=1234")
$1 = 0
(gdb) call (char*) getenv("TEST")
$2 = 0x0
(gdb) detach
(gdb) quit
$] echo "TEST=$TEST"
TEST=

I've found out that putenv doesn't work, but setenv does:

$] sudo gdb -p $$
(gdb) call (int) setenv("TEST", "1234", 1)
$1 = 0
(gdb) call (char*) getenv("TEST")
$2 = 0x55f19ff5edc0 "1234"
(gdb) detach
(gdb) quit
$] echo "TEST=$TEST"
TEST=1234

According to the documentation

int setenv(const char *envname,
           const char *envval,
           int overwrite);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment