CarloC
CarloC

Reputation: 181

stdin/stdout for command launched from a shell

a very basic question about character echoed when typed into a terminal.

Consider for example a Linux system on which the cat command is issued from a shell (e.g. bash). Now, from my understanding, the shell spawns a process to execute cat executable and, at this stage, cat stdin and stdout are attached to terminal.

Now the question: Does the shell continue to receive character from the terminal (eventually echoing them) or just the spawned process (executing cat) only ?

Upvotes: 0

Views: 389

Answers (4)

CarloC
CarloC

Reputation: 181

Thanks for replies,

I've done an "experiment" forcing off terminal (putty) local echo. Launching cat into a shell and sending characters I can see

~ # cat

hello

hello

~ #

for each character I type ('h' 'e' 'l' 'l' 'o') i can see each one on the terminal screen and then hitting Return key I can see the entire word "hello".

Now, IUUC, the first character occurrences on the screen are due to the 'canonical mode' terminal device driver (driver echos them). Then just when i hit Return the accumulated line 'hello' is "seen" by cat and sent from it to the stdout (the terminal screen again)

does it make sense ?

Upvotes: 0

Joni
Joni

Reputation: 111339

The shell does not receive the characters, only the foreground process. But that's not the whole story.

What you type is first processed by the terminal device driver. The driver has two modes of working: canonical and non-canonical. In the canonical mode, which is used when you run cat, the driver echos characters as you type them and accumulates lines of text. This allows some basic editing, like using backspace to delete what you typed. cat does not get to see what you type until you press enter or Ctrl-D.

In the non-canonical mode the terminal just passes characters to the process without interpretation or modification: this is how full-screen apps work.

Upvotes: 1

Karel Kubat
Karel Kubat

Reputation: 1675

The shell will pass the file descriptors (fd's) to the subprocess (cat) but will also transfer control. So as long as cat is running, the shell doesn't do anything, doesn't receive input, and so on.

Technically the shell forks and execs the subprocess in the child fork, then waits for the subprocess to finish. Once that is done, the shell will wait for more input (allowing you to type a next command), and then runs that, etc..

Upvotes: 2

tripleee
tripleee

Reputation: 189638

The foreground process receives input from the terminal. Whichever process is in the foreground is the only one to receive it (unless it contains internal logic to pass it on to another process).

Upvotes: 1

Related Questions