2

Okay, so I have a program (which I did not write and cannot modify) which I am running as a service using systemd on my Ubuntu 16.04 cloud server. It's working great, except that I need to be able to interact with the running program, and the only way the program supports interacting with it is via stdin/stdout. I realize it's pretty unconventional for a service to use only command-line input, but I don't see what other choice I have.

From what I've read here, it's possible to tell a service to use TTY for stdin and stdout, and so I think I've setup my service to do just that:

[Unit]
Description=My Service
After=getty@tty2.service

[Service]
Type=simple
ExecStart=/path/to/my/service
StandardInput=tty
StandardOutput=tty
TTYPath=/dev/tty2
TTYReset=yes
TTYVHangup=yes
Restart=always
RestartSec=5
User=username

[Install]
WantedBy=multi-user.target

Once my service is running (and yes, it's definitely running), I try using the screen command in PuTTY to view /dev/tty2 as described in this answer:

sudo screen /dev/tty2

However, when I do that all I see in PuTTY is a blank screen with no output that I cannot interact with. (And yes, the program generates plenty of output while running.)

So I'm not sure where I've gone wrong, whether it's in the configuration of the service, my usage of the screen command, or with PuTTY itself. I'm not a super experienced user of Linux in general and this is my first time doing anything with TTY, so my understanding is pretty thin.

Walt D
  • 131

1 Answers1

1

This is totally untested (yet), might work though.

After you log in (via SSH with PuTTY or whatever), start a new tmux session (I use tmux, but you can choose screen), as if you'd like to work in a shell within it. The plain command tmux will work but let's name the session:

tmux new-session -s foo

Then find the PID of your service:

pidof service

and use reptyr to attach it to your current terminal which is inside tmux (I guess you may need sudo as well). See this answer of mine for short characteristics of reptyr and what to do to make it work.

reptyr <pid>

If you want to log out, first detach from tmux with Ctrl+B, D (for screen it's Ctrl+A, D). Later you can return to that terminal with

tmux attach-session -t foo

so there's no need to use reptyr again until after the next reboot.


If I were you I would try to run the service inside tmux in the first place, I expect this would straightforwardly bind it to TTY provided by tmux without TTY-related systemd settings. See this: How to run tmux/screen with systemd > 230?

Something like:

…
[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/usr/bin/tmux new-session -d -s foo /path/to/my/service
User=username
…

If this works, you will have to run tmux attach-session … as the right user:

sudo -u username tmux attach-session -t foo