3

Sometimes I have seen when one program (say A) is running in the foreground and printing its output to stdout, I can type another command (say B), and when I press Enter it is run, even though I had not been prompted to type B since A had not finished executing yet. I could do this in the tcsh shell and the end result was that B was executed after A.

What is this feature called? Is this shell specific? How does it work without me typing the command at the prompt?

2 Answers 2

6

This is called typeahead, and it's not shell specific. What you type ends up being buffered in the terminal, and the next time a program running in the terminal is ready for input it reads what is waiting in the buffer. In your example that program is the shell, so it executes the command you typed as if you'd waited for A to finish before typing it.

Some programs will explicitly clear the buffer before accepting input; for example most programs which ask for a password will clear the buffer, to make sure the user knows what was typed (since the input isn't echoed).

2
  • At what level is this feature implemented. In the kernel? Outside the kernel? May 27, 2015 at 9:49
  • For terminals I think it's implemented in the tty layer, in the kernel. I'd have to check but there's probably also an event queue for X events (for non-tty X applications). May 27, 2015 at 14:13
2

It sounds like what you are describing is actually program A running in the background. A process can still print to the terminal even if it is running in the background.

A bash example:

#----background_program----#
#!/bin/bash

for ((i=0;i<=10;i++)); do
    echo "$i"
    sleep 5
done

exit 0

You can run this in the background, see its output popping up on your terminal. After the first output message, your cursor is moved off the prompt. You can then execute other commands in the foreground whilst background_program is still executing:

./background_program &     # '&' to put in background
echo "wut"
echo "foo"
echo "bar"

This will give you something like:

sandbox@Dionysus:~$ ./background_program &
[1] 6197
sandbox@Dionysus:~$ 0
echo "wut"
wut
sandbox@Dionysus:~$ 1
echo "foo"
foo
sandbox@Dionysus:~$ 2
echo "bar"
bar
sandbox@Dionysus:~$ 3
4
5
6
7
8
9
10

I did this in a gnome-terminal but I don't think the behavior is uncommon.

If you were to execute your program A in the foreground, you get exactly what @Stephen said, typeahead. The program is not executed as your command is loaded in the buffer and then interpreted after program A completes.

1
  • The program A is not running in the background. It is a foreground process.
    – Geek
    May 27, 2015 at 10:01

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .