Is there a way for a backgrounded task to inform t

2019-04-02 02:43发布

问题:

I want to write a program that can be run as a backgrounded task (i.e. my-thing &), and that will beautifully provide relevant output when necessary.

However, with background tasks that print to the terminal, there's always this annoying little progression:

bash-3.2$ my-thing &

bash-3.2$ my-thing &
bash-3.2$ -- Hello from my-thing!
-- now let me start doing what I do best ...

… notice that we now have no prompt before the cursor, not to mention that there's an ugly erraneous prompt where my program spat out output while a prompt had already been printed.

Thus, I want three things, only one of which I don't have any idea how to go about doing:

  1. Detect whether my program is being run in the background, and alter my output/operation accordingly (i.e. print out less useless information; queue further information to only be output when the program is foregrounded again; etceteras)
  2. Clear out the prompt (if it already exists) when suddenly printing information to a terminal we've been backgrounded in
  3. Inform the terminal after I've finished whatever I'm printing to the terminal for, somehow forcing it to re-draw a new prompt below the content I've added

The third is the only one I have absolutely no idea how to go about; though I've got some inklings on the other two, any links or suggestions there would be appreciated as well.

Equally appreciated, even, would be links to any programs (any language/environment) which already have modes that operate this; as I could attempt to reverse-engineer/spelunk their implementation.

回答1:

This works for me:

echo 'sleep 1; echo; echo hi' > /tmp/hi
chmod +x /tmp/hi
zsh
/tmp/hi &
asdfsadf # type whatever, here.

After the 'hi' gets echo'd, zsh knows to redraw your prompt with the 'asdfasdf' intact.

So, no big surprise: zsh being better than bash.