2

Let's say I start a program with a non-interactive SSH call (without pseudo-terminal) and exit the session via CTRLC:

$ ssh user@server -- sleep 123
^C

This way, the program, in this case sleep 123 for example, is still running on server, even after the SSH session was terminated:

$ ssh user@server -- ps -ef | grep "sleep 123"
user     12430       1  0 19:28 ?        00:00:00 sleep 123

I am aware of ssh's -t option to have SIGINT sent to the remote sleep instead of the local ssh. But I'm looking for a way to make the remote program stop without having to resort to a pseudo-terminal and specify extra options in the ssh call.

finefoot
  • 2,940
  • 2
  • 21
  • 41
  • If this is tied to the host used, you can get a PTY without specifying `-t` in the commandline by configuring `RequestTTY` in `ssh_config`. Or you can use a shell function or script file to shadow `ssh` and add/alter options as desired. – dave_thompson_085 Jan 19 '23 at 01:26
  • If the reason you don't want a tty is because it mangles binary data and you need to transfer binary data then please check this: [*`ssh` with separate stdin, stdout, stderr AND tty*](https://unix.stackexchange.com/q/653431/108618). – Kamil Maciorowski Jan 19 '23 at 06:50
  • Related: [How to terminate remotely called "tail -f" when connection is closed?](https://unix.stackexchange.com/q/133951) – Stéphane Chazelas Feb 25 '23 at 13:11

1 Answers1

0

I came up with a partial solution for certain cases.

The idea is this: When ssh gets killed on the client, whatever program was being run by the command on server loses its parent process and gets assigned init as its parent process.

So if you're able to edit the program that's running on server to continuously check the parent PID, then you'll notice once it switches to 1 and therefore ssh on the client must have been terminated.

cat <<-"EOF" | ssh user@server sh
while :; do
sleep 1
ppid="$(ps -p "$$" -o ppid= | tr -d "[:blank:]")"
[ "$ppid" = 1 ] && break
done
EOF
finefoot
  • 2,940
  • 2
  • 21
  • 41
  • Or see if reading stdin gives EOF or writing stdout gives SIGPIPE (or if ignored EPIPE); _many_ programs do one or both of these automatically, but not `sleep`. – dave_thompson_085 Jan 19 '23 at 01:26