PDA

View Full Version : Setting an environment variable using setenv()



kill'emall
10-11-2014, 04:08 PM
Hi, all!

I'm trying to set an environmet variable using setenv() function. I'm able to print it when using getenv() within same program, but cannot see it with printenv command in bash after program exits. It seems like variable just set for the program execution time and not exported, how can I export it to be able to use it inside bash Thanks.

phantomotap
10-11-2014, 04:53 PM
O_o

The environment block, for most operating systems, is designed such that changes to the environment are only inherited not propagated. The `setenv' function changes the environment only for the calling process and children. In other words, the behavior you are seeing is the intended behavior.

The propagation of an environment the way you would like presents a major security issue. If you'd tell us about the platform and why you are trying to propagate a change to the environment, someone may be able to help you find a solution.

Soma

Yarin
10-11-2014, 09:10 PM
how can I export it to be able to use it inside bash
You can't; for the reason stated by Soma.

I think that you are being misled by the name of the command "export".

When you export an environment variable in bash, it is not back-propagating the envvar, it is simply setting it's own envvar, just the same as when your program calls setenv().
To see what I mean, do this: Run bash. Run bash again. Export an envvar of your liking. Confirm that it's set. Exit bash. Check the envvar again, it will no longer be what you exported it as.

The only way you can get all the programs to take on an envvar is by updating the users profile, and even then it won't take effect until all the processes are restarted from the new profile (that is, you log out and back in again)

c99tutorial
10-12-2014, 03:02 AM
how can I export it to be able to use it inside bash Thanks.

One possibility is to put the export commands into your $HOME/.bash_profile startup script.

kill'emall
10-12-2014, 03:22 AM
Thank's a lot for your responds. I'm reading a great book "Advanced Linux Programming" and trying to practice on one chapter that explains the environment. What I'm trying to do is to write the program that promts for a variables and sets or unsets them respectively. From the same book I know about the external environ variable. And I think modifying it is the way to make environment variable persistent.
But I think my knowledge will not me allow to play with this :) in near future.