Setting up environment variables in a C programming and accessing via a script
This is my first post and I thank people in advance for helping me find some answers.
I need to write a script and a C program. The script will execute the C program. The C program will setup a set of environment variables that will be used by the script. I am trying to figure out how to write the C program... I've used the setenv in the C program but when I echo the variable from the script it is empty. I also read that the setenv call sets up variables from the parent process forward. This makes me think that accessing the variable from the script won't work.
Anyways, this is what I am doing in the C program:
setenv("ENV_VAR", str, 1);
Then in the bash script I am doing this:
Nothing is printing out. Any ideas or suggestions?
You won't be able to do it that way, environment variables are inherited from the parent process. If your script calls an executable, then that executable is run as a separate process and it can modify it's own environment, but when it exits, those settings are simply gone.
If your script sources another script, then that's a different matter. The second script is simply 'read in' not executed.
You are the 17th bzillionth person to try that, and it will always fail. The environment of a process is private to that process. Any child processes will inherit a copy of the environment, but even this doesn't help you in your unconventional/backward scenario. If you could do what you are trying to do, where would the limit be drawn for what process would be affected by changing the environment? Ultimately, in the Linux process model, all process are children of the init process, so imagine the far reaching effects you could have.
Your plan of having a C program create environment variables is highly unconventional. Normally, a shell is used to set up the environment, and a binary object module (your compiled C code) would inherit those environment variables. Probably your best bet would be to simply emit a string that can be `backticked` by the shell, which sets the required environment variables. Example:
|All times are GMT -5. The time now is 12:12 PM.|