Search code examples
clinuxenvironment-variablesgetenv

C Producer/Consumer application getting environment variables with getenv() not working


I'm writing an application with Producer who makes and sends messages and Consumer who is getting the messages. I have to set environment variable in producer app and read it in consumer app.

In producer app I did this command

putenv("MSG_KEY=15");

And in the consumer app i tried to get the variable like this

char *z=getenv("MSG_KEY");

But it doesn't return any value (I get nil value). If I write the same command in producer it works if I use putenv() few lines before. I think the problem is that it sets variable only locally so I cannot access it from another program but I don't know how to solve it. Don't know if it matters but I'm using Linux system.


Solution

  • Environment variables are private to a process. You cannot set them in one process and expect to read them in another process.

    The only time you can communicate anything via environment variables to another process is from a parent process to a child, and only at the time that the parent spawns the child. The parent may copy, modify, add, or remove environment variables when it spawns the child. From then on they become entirely separated. Change that one process makes to the variables, is not visible to the other.