免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 781 | 回复: 0
打印 上一主题 下一主题

编写简单的Linux服务控制脚本 [复制链接]

论坛徽章:
1
15-16赛季CBA联赛之北控
日期:2022-03-04 22:35:50
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2008-04-29 16:53 |只看该作者 |倒序浏览

作者: sixth 出处:赛迪网 

阅读提示:首先编写了一个用作服务的程序,功能很简单,每隔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
然后编译成可执行文件,我把它命名为: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 "$1" in
start)
    start
    ;;
stop)
    stop
    ;;
restart)
    stop
    start
    ;;
*)
    echo "usage: $0 start|stop|restart"
    exit 0;
esac
所有函数一目了然,调用start()函数在后台启动testService程序,stop()用来停止程序,restart()更是简单的执行了stop()、start()函数。当需要启动或停止服务的时候只需给程序一个start/stop的参数就行了。
这样,这个简单的服务就完成了。


本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/31/showart_641358.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP