How do I close "less" from the outside without it leaving my terminal in a mess?

3

I'm writing a utility that automatically launches less as a subcommand with its output. Some times an error occurs while writing the output, and I would like to automatically close less and display the error normally. However, no matter what signal I try to send to the less process, it either ignores it or closes "uncleanly", i.e. it leaves my terminal unusable. (However, I can fix the terminal by pressing Ctrl+C and writing (blindly) the command stty sane.)

I have tried all the "usual" signals: SIGINT, SIGTERM, SIGQUIT and SIGKILL. The last one obviously would't work, but I tried it anyway. I can't find anything about signals in the man pages for less.

Is it possible to exit less cleanly from the outside?

Hubro

Posted 2017-02-14T17:32:21.007

Reputation: 4 846

You can use a fifo as input for less end write a "q" to it, when you want to quit. – Julian F. Weinert – 2017-02-16T15:50:29.100

@JulianF.Weinert But I'm already using the stdin of less to feed it text. That said, I'm not sure how less is getting input from my keyboard when its stdin is being used for something else... – Hubro – 2017-02-17T13:40:50.327

What if you feed it a "q"? – Julian F. Weinert – 2017-02-17T14:40:54.047

Answers

1

Depending on job control settings, you might be able to first issue a kill -tstp to the less program, then a kill -9. The first signal is caught by less and makes it restore the tty before re-issuing the signal on itself, which normally makes it pause in the background. However, if the default handler for SIGTSTP is to ignore it, less will just continue and set the terminal to raw again.

You might consider running the less in a separate terminal, eg xterm -e sh -c "less /myfile", then you can kill -9 this with no clearup needed.

You can also run less --quit-on-intr (or -K) and then it will exit cleanly on SIGINT, though this will also affect your normal interaction with the output stream.

Otherwise simply put stty sane; tput reset after your kill command.

meuh

Posted 2017-02-14T17:32:21.007

Reputation: 4 273