一、使用到的工具launchctl
1.命令介绍
launchctl可控制macos系统里的启动进程,可以控制服务的自动启动和关闭。
2.常用命令
// 加载进程控制文件
sudo launchctl load .path/../**.plist
// ... load -w ... 设置开机启动并立即启动该服务
// 卸载加载的文件
sudo launchctl unload ...
// 查看加载的服务
launchctl list
3.一般的plist文件放在以下路径:
/Library/LaunchDaemons/ 由管理员定义的守护进程任务项
/Library/LaunchAgents/ 由管理员为用户定义的任务项
~/Library/LaunchAgents/ 由用户自己定义的任务项
/System/Library/LaunchAgents 由Mac OS X为用户定义的任务项
plist文件可以由服务自带的文件复制而来,或者自己编写后放到对应的目录下,文件里描述程序路径和启动参数
加载后,对应用户登陆时就会启动加载配置文件之后的程序,被杀掉后会自动重启,需要停止的时候执行unload即可
4.执行定时脚本|设置开机启动步骤
(1)编写执行脚本
通常brew在安装软件时brew为我们自动生成。
(2)去对应的目录下建立plist文件
(3)加载服务
说明:Agents文件夹下的plist是需要用户登录后,才会加载的,而Daemons文件夹下得plist是只要开机,可以不用登录就会被加载
(4)可以对设置别名方便操作
eg:
vim ~/.bash_profile #编辑添加如下脚本
alias nginx.start=’launchctl load -w ~/Library/LaunchAgents/homebrew.mxcl.nginx.plist’
alias nginx.stop=’launchctl unload -w ~/Library/LaunchAgents/homebrew.mxcl.nginx.plist’
二、nginx开机自启
// 进入当前用户任务项目录下
cd ~/Library/LaunchAgents/
// 将安装好的nginx的homebrew文件复制到当前用户任务目录下
cp /usr/local/Cellar/nginx/nginx版本/homebrew.mxcl.nginx.plist ~/Library/LaunchAgents/
// 设置启动进程并加载
launchctl load -w ~/Library/LaunchAgents/homebrew.mxcl.nginx.plist
// 如果因权限限制无法启动,需修改对应目录权限
sudo chown root:wheel /usr/local/Cellar/nginx/nginx版本/bin/nginx
sudo chmod u+s /usr/local/Cellar/nginx/nginx版本/bin/nginx
三、php-fpm开机自启
// 找到php-fpm.conf文件,一般在/usr/sbin/php-fpm,未配置时默认是在/private/etc/php-fpm.conf,如果不存在应为/private/etc/php-fpm.conf.default,copy后配置即可
// 进入当前用户任务项目录下
cd ~/Library/LaunchAgents/
// 新建 org.php.php-fpm.plist 文件
vim org.php.php-fpm.plist
// 写入以下配置,注意php-fpm路径
<?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>php-fpm</string>
<key>Program</key>
<string>/usr/sbin/php-fpm</string>
<key>KeepAlive</key><true/>
</dict>
</plist>
// 设置启动进程并加载
sudo launchctl load -w ~/Library/LaunchAgents/org.php.php-fpm.plist
// 如果因权限限制无法启动,需修改对应目录权限
sudo chown root:owner ~/Library/LaunchAgents/org.php.php-fpm.plist
sudo chmod +x ~/Library/LaunchAgents/org.php.php-fpm.plist