许多系统守护进程可以使用启动/停止命令启动。我只是好奇启动/停止在 Linux 系统上是如何工作的。假设我写了一个守护程序可执行文件,我应该如何配置它以便在 Linux 中可以通过启动/停止来控制它。
最佳答案
几年前我在 linux (ArchLinux) 中做了一个守护进程,它每天都运行得很好。 有两种方法可以做到这一点。短途和长途:
捷径:
在/etc/systemd/system/中创建一个名为 mydaemon.service 的文件:
/etc/systemd/system/mydaemon.service
[Unit]
Description=This is my first daemon! - Fernando Pucci
After=network.target
[Service]
User=root
WorkingDirectory=/root
Type=oneshotmc
RemainAfterExit=yes
ExecStart=/bin/echo -e "Daemon started"
ExecStop=/bin/echo -e "Daemon Stopped"
[Install]
WantedBy=multi-user.target
此服务只显示守护进程已启动或已停止。您可以根据需要的句子更改回声。
如果你需要运行一些脚本,试试长路:
路途遥远 在某个目录中创建一个文件,例如根文件夹或/usr/lib/systemd/scripts
/root/mydaemon.sh
start() {
<your start sentences here
and here>
}
stop() {
<your stop sentences here
and here>
}
case $1 in
start|stop) "$1" ;;
esac
你必须让它可以运行 (chmod x) (您可以使用 start 或 stop 参数执行它来测试它。)
作为第二步,在 /usr/lib/systemd/system/mydaemon.service
[Unit]
Description=Second daemon of Fernando Pucci
After=network.target
[Service]
User=root
WorkingDirectory=/root
Type=oneshot
RemainAfterExit=yes
ExecStart=/bin/bash -c '/root/mydaemon.sh start'
ExecStart=/bin/echo -e "MyDaemon Started"
ExecStop=/bin/bash -c '/root/mydaemon.sh stop'
ExecStop=/bin/echo -e "MyDaemon Stopped"
[Install]
WantedBy=multi-user.target
启动和停止
systemctl start mydaemon
systemctl stop mydaemon
systemctl status mydaemon
systemctl enable mydaemon
systemctl disable mydaemon
您(和其他人)可以给我发私信寻求帮助。
关于linux - 在 Linux 中注册可由启动和停止命令控制的守护进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38902980/