MacOS不像 Linux 有 /etc/init.d/rc.local 以及 service 的方式可以設置程序隨機啟動,而是使用 plist 文件管理。你可以寫一個plist文件放到~/Library/Launch Agents/下面,文件里描述你的程序路徑和啟動參數,那么這個用戶登錄時就會啟動這個程序了,而且是殺不了的哦,被殺了之后會自動重新啟動
plist文件分布在:
/System/Library/LaunchDaemons/ (System-wide daemons provided by OS X)
其中 apache的httpd程序啟動配置文件 org.apache.httpd.plist 就在這里。
/System/Library/LaunchAgents/ (由Mac OS X為用戶定義的任務項)
/Library/LaunchDaemons (由管理員定義的守護進程任務項 )
/Library/LaunchAgents (由管理員為用戶定義的任務項 )
如果放到/Library/Launch Agents/下面的話,就是一開機就啟動哦~
~/Library/LaunchAgents ( 由用戶自己定義的任務項 )
這些配置文件由程序 launchctl 設置是否加載。
launchctl 簡介
launchctl 管理 MacOS 的啟動腳本,控制啟動計算機時需要開啟的服務。也可以設置定時執行特定任務的腳本,就像Linux cron一樣。
launchctl需要root權限。
launchctl 常用命令
1.顯示當前的啟動腳本
launchctl list
2.開機時自動啟動Apache服務器
sudo launchctl load -w /System/Library/LaunchDaemons/org.apache.httpd.plist
3.設置開機啟動並立即啟動改服務
launchctl load -w **.pist
4. 設置開機啟動但不立即啟動服務
launchctl load **.pist
5. 停止正在運行的啟動腳本
sudo launchctl unload [path/to/script]
6. 再加上-w選項即可去除開機啟動
sudo launchctl unload -w [path/to/script]
執行定時腳本|設置開機啟動步驟
1.寫執行腳本 (通過 brew 安裝軟件 brew 會為我們自動生成。)
2. 去對應的目錄下建立plist文件
3. 加載服務
>1 cd 進入指定 plist 文件目錄
>2 launchctl load *.plist #加載
launchctl unload *.plist #取消
>3 launchctl list #查看服務
對服務設置別名方便操作
- vim ~/.bash_profile #編輯添加如下腳本
- 命名別名(以 nginx 為例)
啟動:alias nginx.start=’launchctl load -w ~/Library/LaunchAgents/homebrew.mxcl.nginx.plist’
關閉:alias nginx.stop=’launchctl unload -w ~/Library/LaunchAgents/homebrew.mxcl.nginx.plist’
重啟:alias nginx.restart=’nginx.stop && nginx.start’
注意點
- 在launchctl list 命令結果中出現的 plist 文件才會有效。
- Agents文件夾下的plist是需要用戶登錄后,才會加載的,而Daemons文件夾下得plist是只要開機,可以不用登錄就會被加載
