2

I am trying to find an equivalent for setenv to use in a C program. What I am trying to do is to modify the values of all the environment variables of the currently running process. I am trying to use putenv but it doesn't change the variables` values in any way. What could I do?

Jorj2014
  • 45
  • 1
  • 6
  • _putenv changes the variables in the process state. A process obviously cannot change the caller's state. – stark Jan 14 '22 at 19:12
  • *"I am trying to use putenv"* - code, as a proper [mcve], that exhibits what you're trying to do, and shows how it seems to fail specific to your claim, should be added to your question. – WhozCraig Jan 14 '22 at 19:13
  • The thing is that I know that the code works, but only in Linux, and I am looking for an alternative in Windows. – Jorj2014 Jan 14 '22 at 19:17

1 Answers1

3

Those are the correct methods for setting the environment variables. The issue you are hitting is that SetEnvironmentVariable which is what is used by the C Runtime setenv does not change system-wide environment variables; only the environment of the currently running process.

Changing the system-wide or per-user environment variables on Windows is normally done using scripts or UI. To modify the system-wide environment variables from a C program, you need (a) to run it with administrator rights, (b) you need to modify the System Registry, and (c) you need to send a WM_SETTINGSCHANGE Win32 message to get the changes picked up by the Windows shell.

Chuck Walbourn
  • 38,259
  • 2
  • 58
  • 81