linux - 在 Linux 中注册可由启动和停止命令控制的守护进程

标签 linux configuration daemon

许多系统守护进程可以使用启动/停止命令启动。我只是好奇启动/停止在 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/

相关文章:

带有 nginx 配置的 PHP-FPM(进程太多)

c - 编写处理任何类型数组的函数

java - 在 Windows 上哪里可以找到 java 应用程序的用户配置文件?

java - 在android中创建一个守护进程

检查修改日期不起作用

linux - 期望使用分离屏幕编写脚本

python - Gtk/python 和可移植性

configuration - Mercurial 编辑器 : "abort: The system cannot find the file specified"

windows - 将 Apache 2.2 作为单个 httpd.exe 运行以进行调试

python - 为什么调用守护进程时 Python check_output() 不返回?