启动前为进程设置环境变量 [英] Set environment variable for the process before startup

查看:71
本文介绍了启动前为进程设置环境变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下情况:

我的 Mac OS 捆绑应用程序使用了一些 3rd 方动态库,而这些库依赖于一些环境变量,我们将其命名为 ENV_VAR.我想将 ENV_VAR 设置为我的应用程序的某个值只是因为如果我为整个系统设置它可能会破坏其他一些应用程序.它应该对用户透明地工作,即他只需双击它就可以从应用程序文件夹中运行我的应用程序.我怎样才能实现它?

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?

注意:动态库在 main 函数开始之前加载,因此在 main 中设置这个变量没有帮助.

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

推荐答案

您可以添加key "LSEnvironment" 到您的应用程序包的 Info.plist.该值可以是包含键和值字符串的字典,当您的应用通过 Launch Services 启动时(例如,从 Finder 或 Dock 但不是从终端),这些键值对将添加到环境中.

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>

然而,在我的测试中(在 Snow Leopard 上),测试有点不稳定,至少在编辑现有应用程序的 Info.plist 时是这样.基本上,启动服务在第一次遇到应用程序时会缓存应用程序的 Info.plist 的这部分,并且不一定识别磁盘上的更改.您有时可以提示它重新读取 Info.plist,例如,复制应用程序包或将其临时移动到不同的文件夹.当然,矫枉过正的解决方案是使用 lsregister 来刷新和重建缓存:

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

此缓存问题不会影响您的最终用户,只会影响您调整 Info.plist.此外,如果您在源 Info.plist 中进行更改,然后使用 Xcode 构建应用程序,它应该不会影响您.

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.

这篇关于启动前为进程设置环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆