在Mac上我们使用[homebrew]包管理工具(http://brew.sh/index_zh-cn.html)来安装和管理开发工具包,例如:mysql、php、redis。只需要一个命令
brew install mysql
它会将所有的包安装到/usr/local/Cellar/
目录下,并将文件软连接到/usr/local/
安装完成后你需要到/usr/local/Cellar/mysql/5.6.26/bin
下找到mysql来启动。但是如果关掉终端,mysql服务也会随之关闭,这样就始终占据了一个终端窗口。
Mac OS 的开机启动方式
launchd
是 Mac OS 下用于初始化系统环境的关键进程,它是内核装载成功之后在OS环境下启动的第一个进程。采用这种方式来配置自启动项很简单,只需要一个plist文件,该plist文件存在的目录有:
- LaunchDaemons
~/Library/LaunchDaemons
用户登陆前运行 plist(程序) - LaunchAgents
~/Library/LaunchAgents
用户登录后运行相应的 plist(程序)
你需要.plist
文件来指定需要开机启动的程序。
以下是开机启动的.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>org.mongodb.mongod</string>
<key>ProgramArguments</key>
<array>
<string>/usr/local/mongodb-2.0.3/bin/mongod</string>
<string>run</string>
<string>--config</string>
<string>/usr/local/mongodb-2.0.3/mongod.conf</string>
</array>
<key>RunAtLoad</key>
<true/>
<key>KeepAlive</key>
<true/>
<key>WorkingDirectory</key>
<string>/usr/local/mongodb-2.0.3</string>
<key>StandardErrorPath</key>
<string>/usr/local/mongodb-2.0.3/log/error.log</string>
<key>StandardOutPath</key>
<string>/usr/local/mongodb-2.0.3/log/mongo.log</string>
</dict>
</plist>
如何编写.plist文件
brew安装的时候已经为你写好.plist
文件。你只需要运行brew info mysql
来查看帮助信息。
brew info mysql
<script type="text/javascript" src="https://asciinema.org/a/44624.js" id="asciicast-44624" async></script>
此时终端会显示如下信息:
==> Caveats
We‘ve installed your MySQL database without a root password. To secure it run:
mysql_secure_installation
To connect run:
mysql -uroot
To have launchd start mysql at login:
ln -sfv /usr/local/opt/mysql/*.plist ~/Library/LaunchAgents
Then to load mysql now:
launchctl load ~/Library/LaunchAgents/homebrew.mxcl.mysql.plist
Or, if you don‘t want/need launchctl, you can just run:
mysql.server start
按照提示,执行ln -sfv /usr/local/opt/mysql/*.plist ~/Library/LaunchAgents
将mysql加入到登陆启动列表
ln -sfv /usr/local/opt/mysql/*.plist ~/Library/LaunchAgents
或者 立即启动mysql launchctl load ~/Library/LaunchAgents/homebrew.mxcl.mysql.plist
launchctl load ~/Library/LaunchAgents/homebrew.mxcl.mysql.plist
启动之后就可以关闭终端了,mysql会在后台运行。
文/lixiaohao(简书作者)
原文链接:http://www.jianshu.com/p/e73978416920