#!/bin/bash#Author:# lovebing#Program:# This script is used to change the status of memcached.#History:#2013/06/27 createdmemcached=/usr/bin/memcachedpid_file=/home/servers/run/memcache/memcached.pidlog_file=/home/servers/log/memcache/memcached.loguser=yorkit_memcacheport=11211max_mem=2048max_con=4096pid=listen_socket=listen_ip_addr=localhostusage="usage: ${0} {start|stop|restart|status}"function log() { msg=${1} if test -z "${msg}" then return 0 fi time=$(date +'%Y/%m/%d %H:%M:%S') echo -e "${time} ${msg}" >> ${log_file} return 0}function check_pid() { if test -f ${pid_file} then pid=$(cat ${pid_file}) ps -A | grep ${pid} >/dev/null 2>&1 if test $? -eq 0 then return 0 else rm -f ${pid_file} pid= return 1 fi fi pid= return 1}function wait_for_pid() { while true do if test ! -f ${pid_file} then echo -n '.' sleep 1 else pid=$(cat ${pid_file}) break fi done return 0}function status() { check_pid if test ${pid} then echo "Memcached of ${user} is running (main pid: ${pid})" else echo "Memcached of ${user} is stopped" fi return 0}function start() { check_pid if test ${pid} then status return 0 fi cmd="${memcached} -d -m ${max_mem} -u ${user} -p ${port} -c ${max_con} -P ${pid_file}" if test ${listen_socket} then cmd="${cmd} -s ${listen_socket}" else cmd="${cmd} -l ${listen_ip_addr}" fi msg="Starting memcached on port ${port} width user ${user}" echo ${msg} && log "${msg}" ${cmd} && wait_for_pid && check_pid if test ${pid} then msg="Memcached is running (main pid: ${pid})" echo ${msg} && log "${msg}" && return 0 fi msg='Failed' echo ${msg} && log "${msg}" return 1}function stop() { check_pid if test -z ${pid} then status return 0 fi msg="Shutting down memcached (main pid: ${pid})" echo ${msg} && log "${msg}" msg='Done' kill -QUIT ${pid} && echo ${msg} && log ${msg} && return 0 msg='Failed' echo ${msg} && log "${msg}" && return 1}function restart() { stop && start && return 0 return 1}function reload() { check_pid if test -z ${pid} then status return 1 fi msg="Reloading memecached (main pid: ${pid})" echo ${msg} && log "${msg}" msg='Done' kill -HUP ${pid} && echo ${msg} && log ${msg} && return 0 msg='Failed' echo ${msg} && log "${msg}" && return 1}case "$1" in 'start') start && exit 0 exit 1 ;; 'stop') stop && exit 0 exit 1 ;; 'restart') restart && exit 0 exit 1 ;; 'reload') reload && exit 0 exit 1 ;; 'status') status && exit 0 exit 1 ;; *) echo ${usage} exit 1esac