Search code examples
cunixenvironment-variablesglib

Set an environment variable from a process that will be visible by all processes


How to set an envirnoment variable from a process that will be visible by all processes? I'm using C with Glib.

I have 10 processes that use the same library. The problem is that in that library a checking procedure (which is CPU hungry) is performed. I want to avoid that library checking procedure to be executed for every process. For the first process that is using the library it will be enough.


Solution

  • This is simply not possible.

    Setting an environment variable (or changing your current environment) is only visible from the children (and descendants) processes of your current process.

    Other processes, in particular the parent process (usually the shell running in the terminal where you start your program) are not affected.

    You might play dirty tricks like e.g. adding lines into $HOME/.bashrc etc. But you should not.

    You just need to document what environment variables are relevant. It is the user's responsibility to set environment variables (perhaps by manually editing his $HOME/.bashrc etc etc). Leave that freedom to your user. Explain to him how to do that and why.

    You edited your question to explain that

    I have 10 processes that use the same library. The problem is that in that library a checking procedure ( which is CPU hungry ) is performed. I want to avoid that library checking procedure to be executed for every process.

    But you definitely should not need to change environment variable for that.

    You could

    1. decide and document that the checking is not performed, unless some particular environment variable (or some program argument) is given

    2. decide that the checking is given a particular file name, and use file locked write to write that file, and use file locked reads to read it again

    3. Have the checking write its result in some known in advance file, and read that file before deciding it you want to make the costly checks

    4. Have one process starting all the others, and inform them about the check (perhaps indeed setting some environment variable or some program argument) or use some Inter Process Communication trick to communicate with the others (you could use sockets, locked files, shared memory, etc etc...)

    5. Do many other tricks.