简体   繁体   English

在启动之前为进程设置环境变量

[英]Set environment variable for the process before startup

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 . 我的Mac OS捆绑了使用一些第三方动态库的应用程序,这些库依赖于某些环境变量,我们将其命名为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. 我只想为我的应用程序设置ENV_VAR为某个值,因为如果为整个系统设置它,可能会破坏其他一些应用程序。 And it should work transparently to the user ie he just run my app from the Application folder by double clicking it. 而且它应该对用户透明,即他只需双击Application文件夹中的应用程序即可运行我的应用程序。 How can I achieve it? 我该如何实现?

NOTE: dynamic libraries are loaded before main functions starts hence setting this variable in the main doesn't help. 注意:动态库会在主要功能启动之前加载,因此在主要功能中设置此变量无济于事。

You can add a key "LSEnvironment" to your app bundle's Info.plist. 您可以在应用程序包的Info.plist中添加键“ LSEnvironment” 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 (eg from the Finder or Dock but not from the Terminal). 该值可以是包含键和值的字符串的字典,当启动服务(例如从Finder或Dock而不是从终端)启动您的应用程序时,这些键值对将添加到环境中。

<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. 但是,在我的测试(在Snow Leopard上)中,至少在编辑现有应用程序的Info.plist时,测试有点困难。 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. 基本上,Launch Services在首次遇到应用程序时会缓存应用程序Info.plist的这一部分,并且不一定能识别磁盘上的更改。 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. 有时您可以提示它重新读取Info.plist,例如,复制应用程序捆绑包或将其临时移动到其他文件夹。 Of course, the overkill solution would be to use lsregister to flush and rebuild the cache: 当然,过大的解决方案是使用lsregister刷新并重建缓存:

/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. 调整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. 另外,如果您在源Info.plist中进行了更改,然后使用Xcode构建了应用程序,那么它也不会影响您。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM