zettelkasten

Search IconIcon to open search
Dark ModeDark Mode

Shell

#lecture note based on 15-213 Introduction to Computer Systems

A programme that runs programmes on behalf of user. Usually console based, but it could be UI. The basic principle is that the shell launches child processes upon input.

Examples

  • sh original unix shell
  • csh/tcsh - BSD Unix C shell
  • bash Bourne-Again shell

H2 Simple Shell

It loops - because we need to keep running stuff
At each iteration - print something, get command, and try to run it

H3 Simple eval function

Given cmdline

  • parse the command line
  • If it’s built in command (echo is bash, e.g.)
    • Run it
  • Else
    • Create child process
    • Put in child process
    • Try to run it
    • If foreground
      • Wait
    • Else background
      • Print it’s running in background
      • Problem: can’t reap children if not waiting for background processes
        • Solution: some mechanism, like signal in Unix, to notify parent of background process
    • If error
      • Handle it somehow

So, we need Exceptional Control Flow

H3 Sync flow when handling child

See Exceptional Control Flow

Try:
On main: run child -> block signal -> add to job list -> unblock
SIGCHILD handler: block signal -> delete from job list -> unblock

Problem:
child could run first and exit, so we would try to delete before adding

Solution:
on main: block SIGCHILD -> run child -> Unblock child’s blocking (since inherited from parent) -> add to job list -> unblock SIGCHILD

Pseudocode:

while (1) {
	block(SIGCHLD);
	launch_child();
	block(ALL);
	addjob();
	unblock();
}