Programming
linux shell unix gdb environment-variables
Updated Fri, 20 May 2022 22:21:11 GMT

Is there a way to change the environment variables of another process in Unix?


On Unix, is there any way that one process can change another's environment variables (assuming they're all being run by the same user)? A general solution would be best, but if not, what about the specific case where one is a child of the other?

Edit: How about via gdb?




Solution

Via gdb:

(gdb) attach process_id
(gdb) call putenv ("env_var_name=env_var_value")
(gdb) detach

This is quite a nasty hack and should only be done in the context of a debugging scenario, of course.





Comments (5)

  • +9 – So this seems to imply that you can indeed change the environment of a process if you attach to the process as GDB does, and then detach. It seems it would be possible to write a program that does only this. — Nov 05, 2008 at 20:43  
  • +3 – "It seems it would be possible to write a program that does only this" Indeed.. it is. — Feb 23, 2010 at 23:22  
  • +2 – It even works on Windows using cygwin, for processes that are not compiled using cygwin! — Oct 05, 2012 at 18:39  
  • +0 – Note that this only works if the process has not permanently cached the value after a prior getenv. — Jun 24, 2013 at 15:12  
  • +3 – On some systems gdb may give the following error: 'putenv' has unknown return type; cast the call to its declared return type; in those cases you should change putenv call to this: call (int) putenv ("env_var_name=env_var_value") — Feb 20, 2019 at 09:33