首页 > 解决方案 > 通过映射到标准输入的套接字与 Systemd 服务通信

问题描述

我正在创建我的第一个后台服务,我想通过套接字与之通信。

我有以下脚本/tmp/myservice.sh

#! /usr/bin/env bash

while read received_cmd
do
    echo "Received command ${received_cmd}"
done

和下面的插座/etc/systemd/user/myservice.socket

[Unit]
Description=Socket to communicate with myservice

[Socket]
ListenSequentialPacket=/tmp/myservice.socket

以及以下服务:

[Unit]
Description=A simple service example

[Service]
ExecStart=/bin/bash /tmp/myservice.sh
StandardError=journal
StandardInput=socket
StandardOutput=socket
Type=simple

这个想法是了解如何与后台服务进行通信,这里使用的是 unix 文件套接字。该脚本在从 shell 启动并读取标准输入时运行良好,我认为通过设置StandardInput = "socket"它会以相同的方式从套接字读取。

尽管如此,当我运行nc -U /tmp/myservice.socket命令时,它会立即返回,并且我有以下输出:

$ journalctl --user -u myservice
-- Logs begin at Sat 2020-10-24 17:26:25 BST, end at Thu 2020-10-29 14:00:53 GMT. --
Oct 29 08:40:16 shiny systemd[1689]: Started A simple service example.
Oct 29 08:40:16 shiny bash[21941]: /tmp/myservice.sh: line 3: read: read error: 0: Invalid argument
Oct 29 08:40:16 shiny systemd[1689]: myservice.service: Succeeded.
Oct 29 08:40:16 shiny systemd[1689]: Started A simple service example.
Oct 29 08:40:16 shiny bash[21942]: /tmp/myservice.sh: line 3: read: read error: 0: Invalid argument
Oct 29 08:40:16 shiny systemd[1689]: myservice.service: Succeeded.
Oct 29 08:40:16 shiny systemd[1689]: Started A simple service example.
Oct 29 08:40:16 shiny bash[21943]: /tmp/myservice.sh: line 3: read: read error: 0: Invalid argument
Oct 29 08:40:16 shiny systemd[1689]: myservice.service: Succeeded.
Oct 29 08:40:16 shiny systemd[1689]: Started A simple service example.
Oct 29 08:40:16 shiny bash[21944]: /tmp/myservice.sh: line 3: read: read error: 0: Invalid argument
Oct 29 08:40:16 shiny systemd[1689]: myservice.service: Succeeded.
Oct 29 08:40:16 shiny systemd[1689]: Started A simple service example.
Oct 29 08:40:16 shiny bash[21945]: /tmp/myservice.sh: line 3: read: read error: 0: Invalid argument
Oct 29 08:40:16 shiny systemd[1689]: myservice.service: Succeeded.
Oct 29 08:40:16 shiny systemd[1689]: myservice.service: Start request repeated too quickly.
Oct 29 08:40:16 shiny systemd[1689]: myservice.service: Failed with result 'start-limit-hit'.
Oct 29 08:40:16 shiny systemd[1689]: Failed to start A simple service example.

我误解了套接字的工作原理吗?为什么read无法从套接字读取?我是否应该使用另一种机制与我的后台服务进行通信(正如我所说,这是我的第一个后台服务,所以我可能会在这里做一些非常规的事情)?

标签: bashsocketssystemd

解决方案


我见过使用 shell 脚本的唯一方法是,ListenStream=而不是ListenSequentialPacket=. (显然,这意味着您丢失了数据包边界,但 shell 读取通常面向读取\n从流结束的行,因此通常不是问题)。

但最重要的是缺少的是额外的Accept一行:

[Socket]
ListenStream=...
Accept=true

据我了解,如果没有这个,服务将被传递一个套接字,它必须首先在该套接字上进行套接字accept()调用,以获取实际的连接套接字(因此出现read错误)。该服务还必须处理所有进一步的连接。

通过 using Accept=true,将为每个新连接启动一个新服务,并将传递立即可用的套接字。但是请注意,这意味着现在必须对服务进行模板化,即调用myservice@.service而不是myservice.service.

(对于数据报套接字,Accept必须默认为 false)。见man systemd.socket


推荐阅读