虽然平时macOS几乎不关机,但使用launchctl来启动service还是有很多好处的,比如:

  1. 可以开机之后自动运行
  2. 可以一直在后台运行而不需要关注它
  3. 后台程序挂了之后会自动再拉起

配置方式:

1)编写plist文件

文件:~/Library/LaunchAgents/hugo.blog.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>hugo.blog</string>
		<key>KeepAlive</key>
		<true/>
		<key>RunAtLoad</key>
		<true/>
		<key>WorkingDirectory</key>
		<string>/Users/scue/source/blogs/hugo-blogs</string>
		<key>ProgramArguments</key>
		<array>
			<string>/usr/local/bin/hugo</string>
			<string>server</string>
			<string>-D</string>
		</array>
		<key>StandardOutPath</key>
		<string>hugo.log</string>
		<key>StandardErrorPath</key>
		<string>hugo.log</string>
	</dict>
</plist>

其中/Users/scue/source/blogs/hugo-blogs是我的Hugo博客目录,把它替换成你自己的。

StandardOutPathStandardErrorPath决定了日志文件的输出,更多配置细节参考man launchd.plist

2)启动服务

$ launchctl load hugo.blog.plist
$ launchctl start hugo.blog
$ launchctl list | grep hugo                                                                                                130 ↵
50549	0	hugo.blog
$ pgrep hugo
50549

OK,搞定~