You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Mac系统上将DotNet作为Daemon运行?

在macOS上将.NET程序作为守护进程运行

一、使用macOS原生launchd(推荐)

launchd是macOS默认的服务管理框架,支持开机自启、异常自动重启,是最稳定的方案。

1. 创建plist配置文件

在~/Library/LaunchAgents/目录下创建一个反向域名格式的plist文件(例如com.yourcompany.yourapp.plist),示例内容:

<?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.yourcompany.yourapp</string>
    <key>ProgramArguments</key>
    <array>
        <string>/usr/local/bin/dotnet</string>
        <string>/path/to/your/app/YourApp.dll</string>
    </array>
    <key>WorkingDirectory</key>
    <string>/path/to/your/app</string>
    <key>RunAtLoad</key>
    <true/>
    <key>KeepAlive</key>
    <true/>
    <key>StandardOutPath</key>
    <string>/var/log/yourapp.log</string>
    <key>StandardErrorPath</key>
    <string>/var/log/yourapp-error.log</string>
    <key>UserName</key>
    <string>your-username</string>
</dict>
</plist>

替换上述内容中的Label、程序路径、工作目录、用户名和日志路径为实际值。

2. 管理服务

  • 加载配置:launchctl load ~/Library/LaunchAgents/com.yourcompany.yourapp.plist
  • 启动服务:launchctl start com.yourcompany.yourapp
  • 查看状态:launchctl list | grep com.yourcompany.yourapp
  • 停止服务:launchctl stop com.yourcompany.yourapp
  • 卸载配置:launchctl unload ~/Library/LaunchAgents/com.yourcompany.yourapp.plist

二、使用Homebrew Services(便捷方案)

若习惯用Homebrew管理系统服务,可采用此方式:

1. 准备工作

确保已安装Homebrew,未安装则通过官方脚本完成安装。

2. 配置并启动服务

若你的.NET程序不是Homebrew官方包,需手动创建服务配置:
在/usr/local/etc/homebrew/services.d/目录下创建yourapp.plist,格式与launchd的plist一致。
之后通过以下命令管理:

  • 启动:brew services start yourapp
  • 停止:brew services stop yourapp
  • 重启:brew services restart yourapp
  • 查看所有服务状态:brew services list

三、临时后台运行(非持久化)

仅需临时后台运行、无需开机自启的场景,可使用nohup:

nohup dotnet /path/to/your/app/YourApp.dll > /var/log/yourapp.log 2>&1 &

此方式下终端关闭后程序仍会运行,但系统重启后需手动重新启动。

关键注意事项

  • 验证.NET运行时安装:执行dotnet --version确认环境正常。
  • 日志权限:确保日志路径对当前用户有写入权限,否则服务启动会失败。
  • 环境变量配置:若程序需特定环境变量,可在plist中添加EnvironmentVariables节点,示例:
<key>EnvironmentVariables</key>
<dict>
    <key>ASPNETCORE_ENVIRONMENT</key>
    <string>Production</string>
</dict>

内容的提问来源于stack exchange,提问作者Christopher James Woods

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 08:15:29