views:

98

answers:

1

I have created a linux service that runs as a deamon (and gets started from /etc/init.d/X). I need to set some environment variables that can be accessed by the application.

Here's the scenario. The application is a bunch of Perl AGI scripts that depend on (and therefore need to run as) asterisk user but asterisk doesn't have a shell. Ideally I'd just set this in /home/asterisk/.bashrc but that doesn't exist for asterisk.

How can I set environment variables for my app in the asterisk user's running environment so that my app can use them?

+5  A: 

Either set them in the startup script (/etc/init.d/yourdaemon), or put a line in that file that looks like:

. /etc/yourdaemon.env

and put the environment variables in that file, using the syntax export VAR=value. (Or, safer, VAR=value; export VAR. Some Linux/Unix systems use shells as /bin/sh that don't understand the former syntax. bash is safe, though.)

larsmans
Tried that approach. The problem am having with that is that '/etc/init.d/yourdaemon' runs as root and so they are not available to my script, which runs as asterisk.
domino
How do you switch users?
larsmans
start-stop-daemon --start --chuid=$USER --exec $DAEMON. This executes the app as $USER
domino
I checked the source code for the Debian version of `start-stop-daemon` and there's only one place where it touches the environment, to reset `HOME`. Can you post the `init.d` script?
larsmans
It worked. I am the one that had not used `export`. Thanks. Just a small point for future users - if there's a file to be sourced when running `/etc/init.d/myscript` it's good practice to add it to `/etc/default/myscript`.
domino
One thing I still don't understand though - how are the variables being exported to my deamons environment even though the init script is run by root?
domino
Every process passes its environment to its child processes. The `start-stop-daemon` program gets its environment from the `init.d` script; then it switches users *internally*, running as user `asterisk` for a short while and preserving its environment; then it starts your daemon. You'd have to use the `env` command explicitly to wipe the environment clean.
larsmans