linux daemon 权限,Linux 自启动服务 daemon实例

近来,都工作在 Linux 上,开始不断接触 Linux

更多的东西,开通这个 space

都很久了,还是留下点东西吧,日后应该对我对别人有点用处的,开通这个space不也是为了这个用途嘛,都是一些技术上的东西,非技术人员还是别看了吧,把你们搞晕了,我可罪过啊~~

今天需要用到 Linux

的自启动服务,在网上查了一些资料、请教了一下同事,总算摆平了。自启动服务是可以让

Linux 在启动是自动运行该程序的服务,用户也可以通过 service program

start|stop 等命令进行启动|停止。程序将会运行于后台。

要想使用自启动服务,一般需要两步,第一步就是程序本身编写需要做一些处理,第二步就是需要写一个shell脚步,启动时运行

#include

#include

#include

#include

#include

int main(int argc,char* argv[]){

pid_t

pid,sid;

pid =

fork();

if(pid<0){

exit(EXIT_FAILURE);

}

if(pid>0){

exit(EXIT_SUCCESS);

}

umask(0);

sid=setsid();

if(sid<0){

exit(EXIT_FAILURE);

}

if((chdir("/"))<0){

exit(EXIT_FAILURE);

}

close(STDIN_FILENO);

close(STDOUT_FILENO);

close(STDERR_FILENO);

while(1){

sleep(2);

}

return

0;

}

第一步就这样了,解析就不多说了。

第二步就是写个shell脚步

其实,在/etc/init.d下就有很多例子了,我也是参考这里面的,依葫芦划瓢就好了

#!/bin/bash

#

# /etc/rc.d/init.d/hello

#

# Starts the hello

#

# chkconfig: 345 44 56

# description: just a sample

# processname: hello

# Source function library.

. /etc/rc.d/init.d/functions

prog="/root/hello"

prog_s="var/lock/subsys/hello"

[ -f $prog ] || exit 0

RETVAL=0

#

# See how we were called.

#

start() {

# Check if it is already running

if [ ! -f $prog_s ]; then

echo -n $"Starting hello: "

daemon $prog

RETVAL=$?

[ $RETVAL -eq 0 ] && touch $prog_s

echo

fi

return $RETVAL

}

stop() {

echo -n $"Stopping hello: "

killproc $prog

RETVAL=$?

[ $RETVAL -eq 0 ] && rm -f $prog_s

echo

return $RETVAL

}

restart() {

stop

start

}

case "$1" in

start)

start

;;

stop)

stop

;;

restart)

restart

;;

condrestart)

if [ -f $prog_s ]; then

restart

fi

;;

status)

status hello

;;

*)

echo $"Usage: $0

{start|stop|status|restart|condrestart}"

exit 1

esac

exit $RETVAL

把这个文件保存到/etc/init.d/下命名为hello就是了。还要加上运行权限

chmod +x hello

现在就可以通过运行 service hello start|stop|status|restart|condrestart 进行运行等操作了。

最后通过命令:

chkconfig --add hello

发服务添加到自启动行列就可以了。

通过 setup 看看system services 里有没有 hello 吧

good luck~~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值