Warm tip: This article is reproduced from serverfault.com, please click

What happend if a program read and write to same buffer?

发布于 2020-11-28 15:19:19

What I encountered is I wrote a sample python script named tt.py:

import time

while True:
    print(123)
    time.sleep(0.5)

I run it by python tt.py &, it will output to terminal 123 on-going. And if I input a character l after several seconds input s, the command ls works fine.

But why, as I know a little bit pseudoterminal: master side and slave side. I thought bash's stdin, stdout, stderr is redirect to slave side. So in my mind, the bash should return command like l123\n123\n...s not found.

So more general question is how bash know which is output which is input when they point to same file descriptor?

Or where I made a misunderstand in this situation, thanks in advance!


Update:

I know stdin and stdout point to different descripor, but they could point to same one right?

So in my mind, python script's stdout to psuedoterminal's slave side, and terminal display streams in master side. Seems what I can't figure out is how terminal stdin goes to bash's stdin. Isn't it first go master side then go slave side then bash?

If so I thougt things will messed up at master side as it receive both python script's output and terminal's input.

Questioner
roachsinai
Viewed
0
Barmar 2020-11-29 00:13:27

A pseudo terminal consists of two independent channels of data, and they each have their own buffers.

There's one channel that transfers data that's written to the slave pty to the master pty. There's another channel that transfers data written to the master pty to the slave pty.

Anything written to the slave side of the pty is read by the process connected to the master side. In this case, it's your terminal application. It displays this data in the terminal window.

Both python and ls are writing to the slave pty, and their outputs get displayed in the window.

When an application reads from the slave pty, it gets what the other process writes to the master side. The terminal application writes what you type on the keyboard, not the output that was sent to the slave side.

So the output of the python script won't be read as input by the shell.

If the two directions weren't independent, every program that produces output and also reads input would get totally confused, since it would end up reading its own output.