歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux管理 >> Linux服務 >> 實例解析:編寫簡單的Linux服務控制腳本

實例解析:編寫簡單的Linux服務控制腳本

日期:2017/3/2 16:55:05   编辑:Linux服務

首先編寫了一個用作服務的程序,功能很簡單,每隔1秒鐘把當前時間寫入一個文件中:
 
   void recordTime()
{
const char pa[256] = "//home//projects//testService//recordTime";
ofstream fout;
fout.open(pa, ios::app);
time_t currTime;
struct tm *tp;
char buf[256];
while(1)
{
currTime = time(NULL);
tp = localtime(&currTime);
strftime(buf, 256, "%B %e, %Y, %H:%M:%S", tp);
fout<<"current time is "<<buf<<endl;
sleep(1);
}
fout.close();
}


 
  然後編譯成可執行文件,我把它命名為:testService.
 
  再在/etc/init.d下放一個腳本文件,這個文件裡面包含了服務啟動、關閉、重啟等的函數實現:
 
   start()
{
echo "start testService"
/home/projects/testService/testService &
exit 0;
}
stop()
{

echo -n "stop testService"
if pkill testService
then

echo " [ok]"

else

echo " [failed]"

fi

}

case "{GetProperty(Content)}" in
start)
start
;;
stop)
stop
;;
restart)
stop
start
;;
*)
echo "usage: {GetProperty(Content)} start|stop|restart"
exit 0;
esac

 
  所有函數一目了然,調用start()函數在後台啟動testService程序,stop()用來停止程序,restart()更是簡單的執行了stop()、start()函數。當需要啟動或停止服務的時候只需給程序一個start/stop的參數就行了。
 
  這樣,這個簡單的服務就完成了

Copyright © Linux教程網 All Rights Reserved