创建一个 mac 的后台进程(daemon)

本文介绍如何在Mac上创建一个简单的守护进程(Daemon),包括编写执行脚本、配置plist文件及使用launchctl进行加载的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Mac中创建守护进程(Daemon)

创建一个可以执行的脚本 hello.sh
touch /Users/oslivan/test/hello.sh
chmod 755 /Users/oslivan/test/hello.sh
## hello.sh start
for((;;))
do
  echo "hello."
  sleep 3
done
## hello.sh end
创建一个 plist, 并通过 launchctl 加载
touch /Users/oslivan/Library/LaunchAgents/com.oslivan.test.hello.plist
## com.oslivan.test.hello.plist start
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
    <dict>
        <key>Label</key>
        <string>com.oslivan.test.hello</string>
        <key>ProgramArguments</key>
        <array>
            <string>/Users/oslivan/test/hello.sh</string>
        </array>
        <key>StandardOutPath</key>
        <string>/Users/oslivan/test/logfile.log</string>
        <key>StandardErrorPath</key>
        <string>/Users/oslivan/test/logfile_error.log</string>
        <key>RunAtLoad</key>
        <true/>
        <key>KeepAlive</key>
        <true/>
    </dict>
</plist>
## com.oslivan.test.hello.plist end
launchctl load /Users/oslivan/Library/LaunchAgents/com.oslivan.test.hello.plist
测试是否启动成功
ps -ef | grep hello
cd /Users/oslivan/test/ && tail logfile.log
参考

Sample Guide
launchd.plist 语法
launchd 教程

转载于:https://www.cnblogs.com/zhangyanpei/p/7136409.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值