DEV Community

Siddhant Khare
Siddhant Khare

Posted on

What are the internal workings of terminal commands?

First, we should have a context that what is Shell, Session.

What are Shell & Sessions

When I say session, I mean shell session, which acts as a layer between the kernel and the user, so whenever you run a command in your terminal emulator, it's the shell (e.g. bash) that listens for them on the PTY slave attached to it, captures them, communicates with the kernel, then writes the output back to the PTY slave, which the TTY driver will see and send it to the PTY master so it can be viewed by the user.

The session leader is the process that is running shell. This session leader is the parent of all other processes in the terminal. When you log out of the terminal, kernel sends SIGHUP (kill -1) to the session leader, which propagates this signal to all child processes.

Each session is handled by a session leader, the shell, which uses a sophisticated protocol of signals and system calls to communicate with the kernel.

When you run any linux command in the terminal, what happens?

  • You start the bash programme as a sub-process and attach it to the slave component after opening the terminal, which requests a pty from the OS, which returns a pair of file descriptors for the master and slave sides.

  • The characters are sent from the terminal emulator to the master side, where they are echoed back to the master and buffered by the TTY driver.

  • The TTY driver copies the characters in the buffer to the slave when you press enter.

  • When you type the command and press enter, the bash will start a child sub-process, perform the command, and write the output to the std output, which also points to the pts.

  • The output from pts will be echoed to the master by the tty driver.

  • The terminal emulator program's user interface will be redrawn to show you the results of the commands you typed.

Code Implementation in JavaScript

Open in Gitpod


What are the internal workings of terminal commands?

You Can see the implementation of commands by just hitting a button below:

Open in Gitpod

Above button would open a Workspace with multiple terminals displaying the working of TTY & Process Trees

Discussion (0)