Changing the environment variables that control a process is normally something you can do only prior to starting the process. In unix-like environments, each process inherits some portion of the environment from its parent process, allowing environment variables to be set on a per-process basis and allowing simple, fine-grained control of processes through environment variables. For example:

CC=/usr/bin/gcc-4.4 make
tells make to use /usr/bin/gcc-4.4 as the C compiler (given a sensibly constructed makefile that is).

Changing environment variables in running processes is difficult/impossible unless the processes itself has some way of being told to do so (i.e. the process can call putenv() or setenv() to change its own environment but there is no simple call like that to influence another program's environment).

Loading a program in a debugger does, however, allow you to make system calls on behalf of that program, so it's possible to use gdb to change the environment of a running process.

There is undoubtedly an easier way to achieve this than the following script and it could probably rewritten more easily as a short C program to attach to the process and then change the environment. But, while clumsy, this does work, so that's enough for now.

Download: chenv

 
 #!/bin/bash
 # 
 # chenv
 #   change the environment of a running process
 #
 # Copyright (c) 2009 Stuart Prescott
 # 
 #   Distributable under the terms of the GPL v2.
 #
 
 if [ $# -ne 3 ]
 then
   echo "Usage: $0 process variable value" 1>&2
   exit 1
 fi
 
 if [[ $1 =~ ^[0-9]+$ ]]
 then
   PID=$1
 else
   PID=$(pgrep $1)
   if [[ $PID =~ ' ' ]]
   then
     echo "E: more than one PID found" 1>&2
     exit 1
   fi
 fi
 
 echo "Modifying $PID to set $2=$3"
 TMPFILE=$(mktemp)
 cat - < $TMPFILE >>EOF
 attach $PID
 call putenv ("$2=$3")
 detach
 EOF
 gdb -batch-silent -x $TMPFILE > /dev/null
 
 rm $TMPFILE

Good luck...


Last edited: Thursday May 27, 2010

Valid XHTML 1.1 Valid CSS 2