Set environment variable for the process before st

2020-04-27 08:12发布

问题:

I have the following situation:

I have Mac OS bundle with application which uses some 3rd party dynamic libraries and those libraries depend on some environment variable, let's name it ENV_VAR. I want to set ENV_VAR to some value for my application only because if I set it for the whole system it may breaks some other apps. And it should work transparently to the user i.e. he just run my app from the Application folder by double clicking it. How can I achieve it?

NOTE: dynamic libraries are loaded before main functions starts hence setting this variable in the main doesn't help.

回答1:

You can add a key "LSEnvironment" to your app bundle's Info.plist. The value can be a dictionary with strings for keys and values and those key-value pairs will be added to the environment when your app is launched by Launch Services (e.g. from the Finder or Dock but not from the Terminal).

<key>LSEnvironment</key>
<dict>
    <key>ENV_VAR</key>
    <string>value</string>
</dict>

However, in my testing (on Snow Leopard), it was a bit flaky to test, at least when editing the Info.plist of an existing app. Basically, Launch Services caches this part of the app's Info.plist when it first encounters the app and won't necessarily recognize changes on disk. You can sometimes prompt it to reread the Info.plist by, for example, duplicating the app bundle or temporarily moving it to a different folder. Of course, the overkill solution would be to use lsregister to flush and rebuild the cache:

/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister -kill -seed

This caching issue won't affect your end users, just you as you tweak the Info.plist. Also, it shouldn't affect you if you make the change in your source Info.plist and then build the app using Xcode.



回答2:

I am not sure if the following works because I don't have such an app to try. The idea is to set the environment variable from the terminal, then call your application:

ENV_VAR=something open -a YourApplication