0

After I call export EXAMPLE="exampleValue" in terminal. I call command printenv I can clearly see my new environment variable.

I compile C program and run it and in code I call getenv("EXAMPLE"). But it returns null every time, unless I call getenv("PATH") or getenv("HOME") or similar environment variables.

char* env_variable_name;
env_variable_name = getenv("EXAMPLE");

Any explanation why I can't get value of EXAMPLE?

I.Step
  • 613
  • 6
  • 22
  • Are you sure it's exported? Try `EXAMPLE=test my_command` – jspcal May 29 '18 at 21:56
  • 1
    Are you running it under the same shell as `printenv`? –  May 29 '18 at 21:56
  • "*unless I call getenv("PATH")*" are you saying `getenv` returns non-null for `"PATH"` or that after you call `getenv("PATH")` the call to `getenv("EXAMPLE")` works? – Ryan Haining May 29 '18 at 21:58
  • getenv("PATH") returns non-null for "PATH". C program is run in the same terminal. – I.Step May 29 '18 at 21:59
  • what about @jspcal's suggestion of running`$ EXAMPLE=test ./a.out` ? – Ryan Haining May 29 '18 at 22:01
  • Thanks @Ryan it worked that way with EXAMPLE=test ./a.out. – I.Step May 29 '18 at 22:11
  • @jspcal Does it mean it is not exported properly? – I.Step May 29 '18 at 22:11
  • 1
    No, it means your shell secures environment and calls `execve()` with predefined set of variables. So, basically what you need is to inherit or access to the parent environment. – 0andriy May 29 '18 at 22:17
  • Possible duplicate of [How does a program inherit environment variables?](https://stackoverflow.com/questions/31034993/how-does-a-program-inherit-environment-variables) Good to read: https://unix.stackexchange.com/questions/130985/if-processes-inherit-the-parents-environment-why-do-we-need-export One more thing is to run the program under non-root user or otherwise. – 0andriy May 29 '18 at 22:21
  • 1
    @0andriy Can you explain a little more about this "secure environment" feature? It sounds like it quietly ignores an `export`, which sounds counterintuitive... – Steve Summit May 29 '18 at 23:20
  • @SteveSummit Perhaps I wasn't clear. Here is more detailed info: https://www.redhat.com/archives/fedora-selinux-list/2009-March/msg00033.html – 0andriy May 30 '18 at 01:35
  • @0andriy: the environment is secured by the kernel, not the shell. And if `EXAMPLE=test ./a.out` works, then so will `export EXAMPLE=test; ./a.out`, since there is no difference in the environment seen by the `exec` call. – rici May 30 '18 at 01:55
  • The comments about selinux wackiness are almost surely unrelated to OP's problem. – R.. GitHub STOP HELPING ICE May 30 '18 at 09:05

0 Answers0