Page Background Animation
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#

  1. 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.
  2. Process Pipelines: Dynamic pipeline execution using pipe(), fork(), and dup2(). The parent process maintains tracking of child PIDs and collects exit statuses via waitpid().
  3. 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.
  4. Builtin Commands: Direct implementations of cd, echo, pwd, export, unset, env, and exit to modify shell state without spawning subprocesses.
  5. 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 using sigaction.
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.