最近使用zookeeper发现, 首次启动zookeeper时, 都会遇到一个错误:spa
$ bin/zkServer.sh startorm
JMX enabled by defaultserver
Using config: /home/nauhcud/workspace/zookeeper/zookeeper/bin/../conf/zoo.cfg进程
Starting zookeeper ... bin/zkServer.sh: 162: cannot create /tmp/zookeeper/zookeeper_server.pid: Directory nonexistentit
FAILED TO WRITE PIDzookeeper
查看进程发现zookeeper进程存在, 并能够正常使用. dataDir "/tmp/zookeeper/" 也在. file
kill掉zookeeper进程从新启动, 一切正常.im
删掉dataDir, 问题依旧.脚本
查看启动脚本, 发现start逻辑以下:word
start)
...
nohup $JAVA "-Dzookeeper.log.dir=${ZOO_LOG_DIR}" "-Dzookeeper.root.logger=${ZOO_LOG4J_PROP}" \
-cp "$CLASSPATH" $JVMFLAGS $ZOOMAIN "$ZOOCFG" > "$_ZOO_DAEMON_OUT" 2>&1 < /dev/null &
if [ $? -eq 0 ]
then
if /bin/echo -n $! > "$ZOOPIDFILE"
then
sleep 1
echo STARTED
else
echo FAILED TO WRITE PID #这句说明写入Pid出现了问题
exit 1
fi
...
纵观整个脚本, dataDir没有出现, 所以, dataDir应该是zookeeper进程内部创建的, 而且有必定延迟, 所以将zookeeper进程id写入到dataDir下的pidfile时, dataDir尚未创建好, 所以就出现了上述状况.
解决办法很简单, 在写入pid以前先判断一下datadir是否存在, 让zookeeper有时间作完初始化, 而后再将pid写入便可.
start)
...
nohup $JAVA "-Dzookeeper.log.dir=${ZOO_LOG_DIR}" "-Dzookeeper.root.logger=${ZOO_LOG4J_PROP}" \
-cp "$CLASSPATH" $JVMFLAGS $ZOOMAIN "$ZOOCFG" > "$_ZOO_DAEMON_OUT" 2>&1 < /dev/null &
zkpid=$!;
if [ $? -eq 0 ]
then
while [ ! -d `dirname $ZOOPIDFILE` ]
do
sleep 1;
done
if /bin/echo -n $zkpid > "$ZOOPIDFILE"
then
sleep 1
echo STARTED
else
echo FAILED TO WRITE PID
exit 1
fi
...