[ACCEPTED]-How can I implement my own basic unix shell in C?-interpreter

Accepted answer
Score: 14

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

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

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

Score: 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 12 are two common choices. Write a recursive 11 descent parser or use yacc(1) to generate one. It's 10 a lot easier to bang out an initial parser 9 using yacc, but you can totally get stuck debugging 8 it and it really wants to be context-free. I 7 prefer recursive descent but just about 6 everyone else in the world prefers using 5 yacc. (Technically, bison.) If the shell is really 4 really simple, like a homework shell, yacc 3 may be overkill.

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

You 1 won't need to use any threads.

Score: 4

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

More Related questions