Set environment variables in C


Is there a way to set environment variables in Linux using C?

I tried setenv() and putenv(), but they don’t seem to be working for me.


I’m going to make a wild guess here, but the normal reason that these functions appear to not work is not because they don’t work, but because the user doesn’t really understand how environment variables work. For example, if I have this program:

int main(int argc, char **argv)
  return 0;

And then I run it from the shell, it won’t modify the shell’s environment – there’s no way for a child process to do that. That’s why the shell commands that modify the environment are builtins, and why you need to source a script that contains variable settings you want to add to your shell, rather than simply running it.

Answered By – Carl Norum

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published