linux笔记06-自启动service

systemctl 管理服务的启动、重启、停止、重载、查看状态等常用命令区分

System V init 命令(RHEL 6)	systemctl 命令(RHEL 7)	作用
service foo start	systemctl start foo.service	启动服务
service foo restart	systemctl restart foo.service	重启服务
service foo stop	systemctl stop foo.service	停止服务
service foo reload	systemctl reload foo.service	重新加载配置文件(不终止服务)
service foo status	systemctl status foo.service	查看服务状态

systemctl 设置服务开机启动、不启动、查看各级别下服务启动状态等常用命令

    System V init 命令(RHEL 6)	systemctl 命令(RHEL 7)	作用
    chkconfig foo on	systemctl enable foo.service	开机自动启动
    chkconfig foo off	systemctl disable foo.service	开机不自动启动
    chkconfig foo	systemctl is-enabled foo.service	查看特定服务是否为开机自动启动
    chkconfig --list	systemctl list-unit-files --type=service	查看各个级别下服务的启动与禁用情况

使用systemctl做一个启动服务

1、在/etc/systemd/system目录下创建对应的service如neptune.service然后按以下内容输入保存.

[Unit]
Description=just for NeptuneRobot 
Wants=network-online.target #启动前必须要启动的模块

[Service]
WorkingDirectory=/home/neptune/NeptuneRobot #配置工作目录
Environment="LD_LIBRARY_PATH=/home/neptune/NeptuneRobot"    #启动前环境变量设置
ExecStart=/home/neptune/NeptuneRobot/NeptuneRobot   #启动的程序
Type=simple
Restart=always
TimeoutSec=infinity
User=neptune    #用户名

[Install]
WantedBy=multi-user.target
Type有如下几种可选项:

simple

forking

oneshot

dbus

notify

idel

  • simple这是默认的Type,当Type和BusName配置都没有设置,指定了ExecStart设置后,simple就是默认的Type设置。simple使用ExecStart创建的进程作为服务的主进程。在此设置下systemd会立即启动服务,如果该服务要启动其他服务(simple不会forking),它们的通讯渠道应当在守护进程启动之前被安装好(e.g. sockets,通过sockets激活)。

  • forking,如果使用了这个Type,则ExecStart的脚本启动后会调用fork()函数创建一个进程作为其启动的一部分。当一切初始化完毕后,父进程会退出。子进程会继续作为主进程执行。这是传统UNIX主进程的行为。如果这个设置被指定,建议同时设置PIDFile选项来指定pid文件的路径,以便systemd能够识别主进程。

  • oneshot,onesh的行为十分类似simple,但是,在systemd启动之前,进程就会退出。这是一次性的行为。可能还需要设置RemainAfterExit=yes,以便systemd认为j进程退出后仍然处于激活状态。

  • dbus,这个设置也和simple很相似,该配置期待或设置一个name值,通过设置BusName=设置name即可。

  • notify,同样地,与simple相似的配置。顾名思义,该设置会在守护进程启动的时候发送推送消息(通过sd_notify(3))给systemd。

2、使用sudo systemctl enable neptune.service开启开机启动服务。

3、使用sudo systemctl start neptune.service立即启动服务

使用shell创建生成自启动服务

#!/bin/bash

CRTDIR=$(pwd)
echo $CRTDIR
export LD_LIBRARY_PATH=$CRTDIR
# ./NeptuneRobot

# 向一个临时文件中写入配置的内容,两种形式service和systemctl
sudo cat >/etc/systemd/system/NeptuneRobot.service<<EOF
[Unit]
Description=just for NeptuneRobot 
Wants=network-online.target #启动前必须要启动的模块

[Service]
WorkingDirectory=$CRTDIR #配置工作目录
Environment="LD_LIBRARY_PATH=$CRTDIR"    #启动前环境变量设置
ExecStart=$CRTDIR/NeptuneRobot   #启动的程序
Type=simple
Restart=always
TimeoutSec=infinity
User=neptune    #用户名

[Install]
WantedBy=multi-user.target
EOF

posted @   alvinlyb  阅读(104)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 没有源码,如何修改代码逻辑?
· NetPad:一个.NET开源、跨平台的C#编辑器
· PowerShell开发游戏 · 打蜜蜂
· 凌晨三点救火实录:Java内存泄漏的七个神坑,你至少踩过三个!
点击右上角即可分享
微信分享提示