通过映射到stdin的套接字与Systemd服务进行通信

时间:2020-10-29 16:02:41

标签: bash sockets 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文件套接字。从外壳启动脚本并读取stdin时,该脚本运行良好,我认为通过设置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无法从套接字读取?我是否应该使用另一种机制与后台服务进行通信(如我所说,这是我的第一个后台服务,所以我可以在这里做一些非常规的事情)?

1 个答案:

答案 0 :(得分:1)

我看到的使用shell脚本的唯一一件事是ListenStream=而不是ListenSequentialPacket=。 (显然,这意味着您会丢失数据包边界,但是读取外壳程序通常是针对从流中读取\n结尾的行,因此通常不会出现问题。)

但是最重要的是缺少的Accept行:

[Socket]
ListenStream=...
Accept=true

据我了解,没有此服务,将向该服务传递一个套接字,它必须首先在该套接字上进行套接字accept()调用,以获取实际的连接套接字(因此发生read错误)。然后,该服务还必须处理所有其他连接。

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

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