编写简单的linux服务

因为有些程序需要从windows转到linux下,而自己对linux又不熟悉,所以请教了同寝好友大概讲了一下如何在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()
{
    pkill testService
    echo "stop testService"
}

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的参数就行了。

     这样,这个简单的服务就完成了。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值