![创建启动和关闭 systemd 守护进程时出现问题](https://linux22.com/image/203386/%E5%88%9B%E5%BB%BA%E5%90%AF%E5%8A%A8%E5%92%8C%E5%85%B3%E9%97%AD%20systemd%20%E5%AE%88%E6%8A%A4%E8%BF%9B%E7%A8%8B%E6%97%B6%E5%87%BA%E7%8E%B0%E9%97%AE%E9%A2%98.png)
我正在尝试为我的设备创建一个配置文件,但是当我在启用并关闭计算机后启动守护程序时,它不起作用。该脚本仅在启动时执行 network.target 之后的 ExecStart 行。编辑:代码:
[Unit]
Description="Service that executes Discord Bot at Boot and Shutdown."
After=network.target
Before=poweroff.target
[Service]
ExecStart=/usr/bin/mi_script_bash.sh start
ExecStop=/usr/bin/mi_script_bash.sh stop
Type=oneshot
RemainAfterExit=true
[Install]
WantedBy= default.target poweroff.target
ExecStart 和 ExecStop 调用用于 bash 脚本 mi_script_bash.sh(用于调用 NodeJs 脚本的简单字符串比较):
#!/bin/bash
[ "$1" == "start" ] && node /home/ser356/Escritorio/discordjs/app.js start
[ "$1" == "stop" ] && node /home/ser356/Escritorio/discordjs/app.js stop
然后是节点脚本:
const {Client,Intents} = require("discord.js");
require('dotenv').config();
var hora=new Date();
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
var argumentos=process.argv[2];
console.log(argumentos)
//client.login("OTUwNTQyNDQ5MzYzODA4MzA2.YiabpA.bulmNmwGgz9s8kOPyvjngR_rSbo");
client.on('ready', () => {
var canal = client.channels.cache.get("950644612517724171")
if(argumentos==='start'){
canal.send("Mi dueño me ha arrancado "+hora);
}
else if(argumentos==='stop'){
canal.send("Mi dueño me requiere "+hora);
}
else{
canal.send("nada")
}
});
client.login('token')
答案1
终于找到了适合我的解决方案。
将 Unit 分为两个守护进程,并为每个守护进程授予 chmod 0644 权限
service_discord.service :
[Unit]
Description="Service that executes Discord Bot at Boot."
After=network.target
[Service]
Type=simple
ExecStart=/usr/bin/mi_script_bash.sh start
[Install]
WantedBy=multi-user.target
其中服务执行After
网络服务,WantedBy=multi-user.target
表示在多用户状态下运行的服务,Type=simple
表示在前台运行的守护进程
一样:
service_discord_end.service
[Unit]
Description="Run Discord Bot at shutdown"
DefaultDependencies=no
Before=shutdown.target
[Service]
ExecStart=/usr/bin/mi_script_bash.sh stop
[Install]
WantedBy=shutdown.target
在这种情况下,DefaultDependency 为 no,因为我们有 Before 选项,但没有默认情况下预期的 after 选项。
看:https://github.com/systemd/systemd/issues/7113#issuecomment-337451441
然后运行:
systemctl daemon-reload
systemctl enable sistema*
systemctl start sistema*
systemctl status sistema* #optional
reboot