23

I'm a newbie to process and thread management. My Shell should understand PATH environment variable. It can be set and modified. It runs in two ways -interactive & batch mode. Shell is capable of taking more than one job like ls;ps;wc file;cal. I want to get my hands dirty on signals too. So I should handle ^K , ^c as well.

I know I will have to use execs, forks and pipes but just can't get started.

Andrew T.
  • 4,701
  • 8
  • 43
  • 62
Alex Xander
  • 3,903
  • 14
  • 36
  • 43

3 Answers3

14

All the unix shells are open-source - so a good place to start may be to read the code.

If you're looking for a good starter article on the subject try Writing Your Own Shell from the Linux Gazette.

Another good starting point is to take a look at the source code of mini-shell just because its one of the smallest to get your head round.

Supertux
  • 8,088
  • 10
  • 42
  • 47
8

Your main loop is:

  • read a line (use fgets(3) for a simple shell, readline(3) for a fancy one)
  • parse the command
  • fork and execute the pipelines

To parse the command, there are two common choices. Write a recursive descent parser or use yacc(1) to generate one. It's a lot easier to bang out an initial parser using yacc, but you can totally get stuck debugging it and it really wants to be context-free. I prefer recursive descent but just about everyone else in the world prefers using yacc. (Technically, bison.) If the shell is really really simple, like a homework shell, yacc may be overkill.

To do the lexical analysis you can also roll your own or use flex.

You won't need to use any threads.

DigitalRoss
  • 143,651
  • 25
  • 248
  • 329
  • 3
    I would recommend `readline()` be used in any case - it will make your life infinitely easier as long as you have to use said shell. But +1 for getting bogged down in yacc/bison. Good tools, but it's a hard task to simplify. – Chris Lutz Sep 30 '09 at 19:04
  • If you just want to execute programs from yoyur shell, then you don't need a parser & lexer ... however if you do want to do "other" things then I suggest you to use flex+yacc ... *do not roll your own* – aviraldg Sep 30 '09 at 19:09
  • 1
    Am getting it. But I want to get my hands dirty on signals too. So I should handle ^K , ^c as well. – Alex Xander Sep 30 '09 at 19:13
4

Many of the Unix books that describe the main system calls also implement a shell to illustrate how and why you might use the various calls. Stevens and Rochkind are two such books:

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278