in reply to Systemd socket activated service in perl

The article you linked is an example where systemd passes the listen socket to the service. The service would still need to accept connections and fork off children to handle them. Are you sure that systemd offers a mode where it accepts and launches a new service each time a connections is received?

If your main goal is to let long-lived processes keep running on an old version while a new version is deployed and new connections use the new code, all you really need to do is execute a new perl process instead of forking. Or in other words, fork like you do above, then exec($^X, $script_name, @args); and put sub handle_connection in that script file. You can replace the file at any time and new connections get the new implementation without interrupting current ones.


So... I was curious and asked ChatGPT. It thinks your solution could be this simple:

If you're looking for a setup similar to inetd, where a new process is spawned for each incoming connection, systemd has a feature called socket-activated services with per-connection instances. This is achieved by using the Accept=yes option in the socket unit file. Here's a simplified example: Create a socket unit file, let's say example-socket.socket:
[Unit] Description=Example Socket [Socket] ListenStream=12345 Accept=yes [Install] WantedBy=sockets.target
This sets up a socket to listen on port 12345 and spawns a new service for each incoming connection. Create a service unit file, for example example-service@.service:
[Unit] Description=Example Service [Service] ExecStart=/path/to/your/executable StandardInput=socket
Note the %i in the service file, which represents the instance identifier. systemd will replace this with a unique identifier for each connection. Enable and start the socket:
systemctl enable example-socket.socket systemctl start example-socket.socket
Now, systemd will spawn a new service instance for each incoming connection on the specified socket.
If that is correct (which clearly it forgot to use a '%i' in the service file... and I don't see any linkage between the socket unit and the service unit...) then the top-level of your script could be reduced to just
handle_conenction(\*STDIN);

Replies are listed 'Best First'.
Re^2: Systemd socket activated service in perl
by tybalt89 (Monsignor) on Jan 20, 2024 at 12:20 UTC

    The linkage is the name of the units, in this case 'example-socket'. It can be overridden, but it is the default.

    UPDATE: note that a wrong file name is given by chatGPT - 'example-server@.service' should be 'example-socket@.service'