Changing Environment Variable of a Running Process

Changing environment variable of a running process

In general, you can only influence a process's environment variables at the time the process starts up. If you need to communicate a change to a running process, the environment isn't the right tool.

However, this question has some answers that suggest ways to overcome this limitation.

Edited to add in light of discussion in the question's comments: A fairly good way of communicating occasionally changing setup to a running process is to designate a configuration file where the LOGLEVEL value is set, send a SIGHUP to the process, and have the process reread the configuration file upon receipt of SIGHUP.

Change environment variable value during execution

You can change the value during runtime - from inside the ruby script - using:

ENV['VARIABLE_NAME'] = 'value'

There is no option to change environment values from outside the process after it has been started. That's by design, as the environment will be passed at process startup.

Setting environment variables for a specific run of a specific process

Assuming you are prepared to rely on the Windows API, when you call the CreateProcess function to launch a process, you have the lpEnvironment parameter.

Normally you pass NULL which means, use the environment of the creating process. However, you can supply an environment block which will be used by the new process.

The environment block that you pass is a null-terminated block of null-terminated strings. For example:

"MyVar=MyValue\0MyOtheVar=MyOtherValue\0\0"

defines two separate variables.

Injecting Variables into a running Process

It appears that local IPC implementations like shared memory is the way to go: Fastest technique to pass messages between processes on Linux?

running multiple processes, each with a different set of values for the environment variable

It is unclear to me what you want, but lets see if we together can build it.

app1() {
export OMP_NUM_THREADS=$1
sleep 1
echo app1 $OMP_NUM_THREADS
}
app2() {
export OMP_NUM_THREADS=$1
sleep 1
echo app2 $OMP_NUM_THREADS
}
app3() {
export OMP_NUM_THREADS=$1
sleep 1
echo app3 $OMP_NUM_THREADS
}
app4() {
export OMP_NUM_THREADS=$1
sleep 1
echo app4 $OMP_NUM_THREADS
}
export -f app1 app2 app3 app4

parallel app{1} {2} ::: 1 2 3 4 :::+ 2 3 5 7

Or compute OMP_NUM_THREADS based on job number using Perl code

seq 4 | parallel app{} '{= $_= seq()*seq()+1 =}' 

To guarantee that not two jobs use the same value (often used for CUDA_VISIBLE_DEVICES), you can use the job slot number:

# 0..3
seq 10 | parallel -j 4 'CUDA_VISIBLE_DEVICES={= $_=slot()-1 =} app{}'

Or:

# 1..4
seq 10 | parallel -j 4 'app{} {%}'


Related Topics



Leave a reply



Submit