-   Programming (
-   -   Setting up environment variables in a C programming and accessing via a script (

mateo14 02-16-2010 11:28 PM

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:

echo $ENV_VAR

Nothing is printing out. Any ideas or suggestions?
Thanks again,

kbp 02-16-2010 11:44 PM

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.


theNbomr 02-16-2010 11:54 PM

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:

#! /bin/sh
# Your program is called LQmateo14, and it prints to stdout:
# "ONEVAR=one2three\n"
# "TWOVAR=two3four\n"
echo $ONEVAR
echo $TWOVAR

--- rod.

All times are GMT -5. The time now is 08:12 AM.