254 words
1 minute
Minishell — UNIX Shell Implementation in C
Minishell: Process Control and POSIX Shell Implementation
Minishell reproduces the core mechanics of GNU Bash in C, implementing process lifecycle management, input tokenization, AST evaluation, file descriptor redirections, and signal dispatching.
Architecture and Execution Pipeline
graph LR Input[Raw Line Input] --> Lexer[Lexical Tokenizer] Lexer --> Parser[Command List / Tree] Parser --> Expander[Variable Expander] Expander --> Executor[Executor fork / execve / pipes] Executor --> Output[Process Output & Exit Code]Core Components
- Lexing and Parsing: Tokenizes raw strings while handling quoting states (single quotes preserve literal values, double quotes allow environment variable expansion). Syntactic verification ensures valid redirection targets and pipe placements.
- Process Pipelines: Dynamic pipeline execution using
pipe(),fork(), anddup2(). The parent process maintains tracking of child PIDs and collects exit statuses viawaitpid(). - Redirections:
<: Redirects standard input.>: Truncates and redirects standard output.>>: Appends and redirects standard output.<<: Heredoc parsing writing into temporary anonymous pipes until the delimiter token is met.
- Builtin Commands: Direct implementations of
cd,echo,pwd,export,unset,env, andexitto modify shell state without spawning subprocesses. - Signals: Setting terminal line discipline and handling
SIGINT(Ctrl+C),SIGQUIT(Ctrl+), and EOF (Ctrl+D) correctly in both interactive prompt and child process execution modes usingsigaction.
void execute_pipeline(t_command *cmd, int prev_fd) { int pipefd[2]; if (cmd->next && pipe(pipefd) == -1) handle_error("pipe failure");
pid_t pid = fork(); if (pid == 0) { if (prev_fd != -1) { dup2(prev_fd, STDIN_FILENO); close(prev_fd); } if (cmd->next) { close(pipefd[0]); dup2(pipefd[1], STDOUT_FILENO); close(pipefd[1]); } execute_single_cmd(cmd); }}Memory Management
All dynamically allocated abstract syntax structures and environment copies are freed upon command completion, verified with Valgrind leak detection under high-stress inputs.
Sphynx | Ismail Larhrib