在macOS中以编程方式启用,禁用和启动服务 [英] Enable, disable and start services programmatically in macOS
问题描述
我正在编写服务附带的程序.到目前为止,我要做的是创建一个助手工具,该工具可以为我的流程运行提升的任务并可以通过XPC进行通信.
I am writing a program that comes with a service. What I did so far is to create a helper tool that can run elevated tasks for my process and can communicate via XPC.
我的程序与服务捆绑在一起,我想使用帮助器工具来安装和启动/停止该服务,以便我的程序在设置中可以有一个复选框使用系统启动服务".
My program comes bundled with a service and I want to use the helper tool to install and start/stop this service so my program can have a checkbox "start service with system" in the settings.
我可以成功复制该服务的plist,但是找不到以编程方式启用,禁用,启动或停止该服务的任何方法.我认为调用system("launchctl load /path/to/service.plist");
的解决方案非常难看.目标C中是否有任何机制可以完成此任务并获得成功或失败的结果?
I can successfully copy the plist for the service, but I cannot find any way to enable, disable, start or stop the service programmatically. I think the solution to call system("launchctl load /path/to/service.plist");
pretty ugly. Is there any mechanism in objective C to accomplish this task and get a success or failed result?
推荐答案
Apple已弃用C API,用于启动,停止和启用launch.h
中的已启动服务. API的源代码位于其开放源代码站点上: https://opensource.apple.com/source/launchd/launchd-442.26.2/liblaunch/
Apple has a deprecated C API for starting, stopping, and enabling launchd services in launch.h
. The source code for the API is on their opensource site: https://opensource.apple.com/source/launchd/launchd-442.26.2/liblaunch/
这里有一些示例代码要求启动以启动LittleSnitchUIAgent服务:
Here's some sample code that asks launchd to start the LittleSnitchUIAgent service:
#include <launch.h>
int main(int argc, const char * argv[]) {
const char *job = "at.obdev.LittleSnitchUIAgent";
launch_data_t resp, msg;
msg = launch_data_alloc(LAUNCH_DATA_DICTIONARY);
launch_data_dict_insert(
msg, launch_data_new_string(job), LAUNCH_KEY_STARTJOB);
resp = launch_msg(msg);
launch_data_free(msg);
return 0;
}
LittleSnitchUIAgent不是指-我从本地服务列表中随机选择了它.我将错误检查留在了样本之外,以保持其直截了当.
The LittleSnitchUIAgent isn't signification -- I chose it at random from my local list of services. I left error checking out of the sample to keep it straight forward.
如果您还没有,我建议给启动手册页和进行了非常仔细的研究. Launchd可以响应几乎所有内容来启动您的进程:计时器,套接字连接,正在添加到系统中的设备等等.实际上很少需要管理自己的服务.我无法确认这一点,但我怀疑这就是为什么他们不赞成使用API.
If you haven't already I would recommend giving the launchd man pages and the Daemons and Services Programming Guide a very close study. Launchd can start your processes in response to almost anything: a timer, a socket connection, a device being added to the system, among many others. It's rare that you actually need to manage your own services. I haven't been able to confirm this but I suspect that's why they've deprecated the API.
这篇关于在macOS中以编程方式启用,禁用和启动服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!