实例解析:编写简单的Linux服务控制脚本
点击次数:21 次 发布日期:2008-11-21 23:23:58 作者:源代码网
|
源代码网推荐
首先编写了一个用作服务的程序,功能很简单,每隔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的参数就行了。 这样,这个简单的服务就完成了
源代码网供稿. |