{"id":51284845,"url":"https://github.com/yomazini/42cursus-minishell","last_synced_at":"2026-06-30T04:30:53.882Z","repository":{"id":350330678,"uuid":"1010434403","full_name":"yomazini/42cursus-minishell","owner":"yomazini","description":"custom implementation of a basic Unix shell, similar to bash, written in C. This project focuses on parsing and executing commands, managing file descriptors for I/O redirection (\u003c, \u003e, |), and handling environment variables and built-in functions like cd, echo, and exit. It's a deep dive into process creation, signal handling.","archived":false,"fork":false,"pushed_at":"2026-04-09T21:02:17.000Z","size":26046,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"master","last_synced_at":"2026-04-09T23:10:01.561Z","etag":null,"topics":["42cursus","bash","command-line","execution","ipc","minishell","minishell-42","minishell42","parsing","process-manager","shell","system-call","unix"],"latest_commit_sha":null,"homepage":"","language":"C","has_issues":false,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/yomazini.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-06-29T04:09:01.000Z","updated_at":"2026-04-09T21:02:20.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/yomazini/42cursus-minishell","commit_stats":null,"previous_names":["yomazini/42cursus-minishell"],"tags_count":null,"template":false,"template_full_name":null,"purl":"pkg:github/yomazini/42cursus-minishell","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yomazini%2F42cursus-minishell","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yomazini%2F42cursus-minishell/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yomazini%2F42cursus-minishell/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yomazini%2F42cursus-minishell/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/yomazini","download_url":"https://codeload.github.com/yomazini/42cursus-minishell/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yomazini%2F42cursus-minishell/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":34952850,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-26T15:22:16.424Z","status":"online","status_checked_at":"2026-06-30T02:00:05.919Z","response_time":92,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["42cursus","bash","command-line","execution","ipc","minishell","minishell-42","minishell42","parsing","process-manager","shell","system-call","unix"],"created_at":"2026-06-30T04:30:53.142Z","updated_at":"2026-06-30T04:30:53.876Z","avatar_url":"https://github.com/yomazini.png","language":"C","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Minishell - A Custom Shell Implementation\n\n![42 School Badge](https://img.shields.io/badge/42-School-blue)\n![Norminette](https://img.shields.io/badge/Norminette-passing-success)\n![Score](https://img.shields.io/badge/Score-101%2F100-brightgreen)\n\n\u003e *\"As beautiful as a shell\"* - Creating a fully functional Unix shell from scratch\n\n## 👥 Project Team\n\n### Executor\n- **Youssef Mazini** - Execution Architecture \u0026 Implementation\n  - 🎓 42 Intra: [ymazini](https://profile.intra.42.fr/users/ymazini)\n  - 🐙 GitHub: [yomazini](https://github.com/yomazini)\n  - 💼 LinkedIn: [Connect with me](https://www.linkedin.com/in/youssef-mazini/)\n  \n### Parser\n- **El Mehdi El Garouaz** - Parsing Engine \u0026 Tokenization\n  - 🎓 42 Intra: [eel-garo](https://profile.intra.42.fr/users/eel-garo)\n  - 🐙 GitHub: [MEHDIJAD](https://github.com/MEHDIJAD/)\n  - 💼 LinkedIn: [Connect with me](https://www.linkedin.com/in/el-mehdi-el-garouaz-a028aa287/)\n\n\n---\n\n![Video](./docs/minishell.gif)\n\n\n## 🎯 Project Overview\n\nMinishell is a comprehensive shell implementation that replicates core functionality of bash. This project demonstrates advanced system programming concepts including process management, signal handling, memory management, and complex parsing algorithms.\n\n### 🎯 Key Objectives\n- **Process Management**: Fork, exec, and wait operations for command execution\n- **Advanced Parsing**: Complex tokenization with quote handling and variable expansion\n- **Pipeline Implementation**: Multi-command pipe chains with proper file descriptor management\n- **Signal Handling**: Proper Ctrl-C, Ctrl-D, and Ctrl-\\ behavior\n- **Memory Safety**: Zero memory leaks (excluding readline library)\n- **Error Handling**: Comprehensive error management with proper exit codes\n\n---\n\n## 🏗️ Architecture Overview\n\n## Linux Terminals TTY PTY \u0026 Shell\n\n![terminal \u0026 shell pty](./docs/terminal%20and%20shell%20PTY%20{slave%20and%20master}.png)\n\n### System Architecture\n\n```\n┌─────────────────────────────────────────────────────────────┐\n│                    MINISHELL ARCHITECTURE                  │\n├─────────────────────────────────────────────────────────────┤\n│  Input Layer    │  Parsing Layer   │  Execution Layer      │\n│                 │                  │                       │\n│  ┌─────────────┐│  ┌─────────────┐ │  ┌─────────────────┐  │\n│  │ Readline    ││  │ Tokenizer   │ │  │ Command         │  │\n│  │ History     ││  │ Syntax      │ │  │ Dispatcher      │  │\n│  │ Signals     ││  │ Validator   │ │  │                 │  │\n│  └─────────────┘│  └─────────────┘ │  └─────────────────┘  │\n│                 │                  │                       │\n│  ┌─────────────┐│  ┌─────────────┐ │  ┌─────────────────┐  │\n│  │ Prompt      ││  │ Expander    │ │  │ Pipeline        │  │\n│  │ Management  ││  │ Variable    │ │  │ Manager         │  │\n│  │             ││  │ Resolution  │ │  │                 │  │\n│  └─────────────┘│  └─────────────┘ │  └─────────────────┘  │\n│                 │                  │                       │\n│                 │  ┌─────────────┐ │  ┌─────────────────┐  │\n│                 │  │ Command     │ │  │ Built-in        │  │\n│                 │  │ Table       │ │  │ Commands        │  │\n│                 │  │ Builder     │ │  │                 │  │\n│                 │  └─────────────┘ │  └─────────────────┘  │\n└─────────────────────────────────────────────────────────────┘\n\n```\n\n## 🔧 Core Components\n\n### 📁 Project Structure\n\n```\nminishell/\n├── 📁 execution/           # Execution engine implementation\n│   ├── 📁 built_in/        # Built-in command implementations\n│   │   ├── cd_built_in.c         # Directory navigation\n│   │   ├── echo_built_in.c       # Echo command with -n option\n│   │   ├── env_built_in.c        # Environment display\n│   │   ├── exit_built_in.c       # Shell termination\n│   │   ├── export_built_in.c     # Environment variable export\n│   │   ├── pwd_built_in.c        # Working directory display\n│   │   └── unset_built_in.c      # Environment variable removal\n│   ├── 📁 execution_part/  # Core execution logic\n│   │   ├── executor.c            # Main execution coordinator\n│   │   ├── pipeline.c            # Pipeline execution manager\n│   │   ├── redirections.c        # I/O redirection handler\n│   │   ├── 📁 heredoc/           # Here-document implementation\n│   │   └── find_path.c           # PATH resolution system\n│   └── exec_header.h       # Execution module definitions\n├── 📁 parser/              # Parsing engine implementation\n│   ├── 📁 tokenize/        # Tokenization system\n│   │   ├── tokenizer.c           # Main tokenization logic\n│   │   ├── ft_split_tokens.c     # Token splitting algorithm\n│   │   └── ft_synax_error_free.c # Syntax validation\n│   ├── 📁 expander/        # Variable expansion system\n│   │   ├── expander.c            # Main expansion coordinator\n│   │   ├── ft_expand.c           # Variable expansion logic\n│   │   └── ft_build_variable_name.c # Variable name construction\n│   ├── 📁 cmd/             # Command table management\n│   │   ├── ft_create_cmd_table.c # Command structure building\n│   │   └── ft_cmd_utils.c        # Command utility functions\n│   └── parser.h            # Parser module definitions\n├── 📁 utils/               # Utility functions library\n└── 📁 includes/            # Global header files\n```\n\n### 🏛️ Data Structures\n\n#### Core Shell Data Structure\n```c\ntypedef struct s_data\n{\n    t_env   *env_list;              // Environment variables linked list\n    int     last_exit_status;       // Last command exit status ($?)\n    bool    herdoc;                 // Heredoc processing flag\n    int     peak;                   // Parsing lookahead position\n    bool    field_splitting_needed; // IFS field splitting flag\n    bool    echo_pipe_flag;         // Echo in pipeline context\n    bool    print_flag;             // Output control flag\n    bool    no_split;               // Disable field splitting\n} t_data;\n```\n\n#### Token Structure\n```c\ntypedef struct s_token\n{\n    t_token_type    type;           // Token classification\n    char            *value;         // Token string value\n    bool            exp_in_herdoc;  // Expand in heredoc flag\n    bool            empty_tkn;      // Empty token marker\n    struct s_token  *next;          // Linked list pointer\n} t_token;\n```\n\n#### Command Structure\n```c\ntypedef struct s_cmd\n{\n    char            **argv;         // Command arguments array\n    struct s_redir  *redir;         // Redirection list\n    struct s_cmd    *next;          // Pipeline next command\n} t_cmd;\n```\n\n#### Environment Variable Structure\n```c\ntypedef struct s_env\n{\n    char            *name;          // Variable name\n    char            *value;         // Variable value\n    int             flag_env;       // Environment visibility flag\n    struct s_env    *next;          // Linked list pointer\n} t_env;\n```\n\n---\n\n## 🔍 Parsing Engine\n\n### Tokenization Process\n\nThe parsing engine implements a sophisticated multi-stage tokenization system:\n\n#### Stage 1: Lexical Analysis\n- **Character Classification**: Identifies operators, quotes, whitespace, and word characters\n- **Quote State Management**: Tracks single and double quote contexts\n- **Operator Recognition**: Detects pipes, redirections, and compound operators\n\n#### Stage 2: Syntax Validation\n```c\nint ft_synax_error_free(const char *line)\n{\n    // Validates:\n    // - Unclosed quotes\n    // - Invalid pipe placement\n    // - Malformed redirections\n    // - Empty command sequences\n}\n```\n\n#### Stage 3: Token Creation\n- **Dynamic Memory Allocation**: Efficient token buffer management\n- **Type Classification**: Assigns appropriate token types\n- **Metadata Preservation**: Maintains expansion and quote information\n\n### Variable Expansion System\n\n#### Expansion Types Supported:\n1. **Environment Variables**: `$HOME`, `$PATH`, `$USER`\n2. **Exit Status**: `$?` - Last command exit code\n3. **Quoted Context**: Different behavior in single vs double quotes\n\n#### Expansion Algorithm:\n```c\nchar *ft_build_expanded_string(const char *origin, t_data *data)\n{\n    // 1. Scan for $ characters\n    // 2. Determine expansion context (quoted/unquoted)\n    // 3. Extract variable name\n    // 4. Resolve variable value\n    // 5. Substitute and continue\n}\n```\n\n### Quote Handling\n\n#### Single Quotes (`'`)\n- **Literal Preservation**: All characters preserved exactly\n- **No Expansion**: Variables not expanded\n- **Nested Handling**: Proper nesting with double quotes\n\n#### Double Quotes (`\"`)\n- **Variable Expansion**: `$` expansions processed\n- **Escape Sequences**: Limited escape processing\n- **Whitespace Preservation**: Spaces maintained within quotes\n\n### Field Splitting (IFS)\n\nThe shell implements sophisticated field splitting based on Internal Field Separator rules:\n\n```c\nvoid ft_applay_ifs(t_token **curr_tkn_ptr)\n{\n    // 1. Check if splitting needed\n    // 2. Split on whitespace boundaries\n    // 3. Create new token nodes\n    // 4. Update token list structure\n}\n```\n\n```mermaid\nflowchart TD\n subgraph SG_PARSE_EXPAND[\"parse_and_expand\"]\n    direction LR\n        PE1{\"ft_syntax_error_free sh_vars.line\"}\n        PE_ERR1[\"data.last_exit_status = 258, return false\"]\n        PE2{\"ft_tokenize sh_vars.line\"}\n        PE_ERR2[\"data.last_exit_status = 0/258, return false\"]\n        PE3{\"ft_expander \u0026sh_vars.tkn_list, data\"}\n        PE_OK[\"return true\"]\n  end\n subgraph SG_PROCESS_EXPANSION[\"ft_process_expansion \u0026state, org_str\"]\n    direction TB\n        PROCEXP1[\"curr_char_vl = org_str[*i_ptr]\"]\n        PROCEXP_QUOTE_HANDLE{\"Is curr_char_vl a quote? Enter/Exit quote state\"}\n        PROCEXP_UPDATE_QUOTE[\"Update *st-\u003eqt_ptr and increment (*st-\u003ei_ptr)\"]\n        PROCEXP_DOLLAR_CHECK@{ label: \"curr_char_vl == '$' AND expandable context?\" }\n        PROCEXP_HANDLE_DOLLAR[\"ft_handle_dollar_expansion st, org_str\"]\n        PROCEXP_END_ITER{\"Return *st-\u003eptr != NULL\"}\n        PROCEXP_APPEND_LITERAL[\"Append character from org_str at i_ptr to *st-\u003eptr\"]\n  end\n subgraph SG_BUILD_EXP_STR[\"ft_build_expanded_string origin, data\"]\n    direction TB\n        BES1@{ label: \"new_str = , i = 0, quote_char = '\\\\0'\" }\n        BES_LOOP{\"Loop over origin\"}\n        BES_SKIP_ESC_QUOTE{\"Check if $ is outside quotes\"}\n        BES_INC_I[\"i++, continue loop\"]\n        BES_PROC_EXP[\"ft_process_expansion \u0026state, origin\"]\n        SG_PROCESS_EXPANSION\n        BES_RET_NULL[\"Return NULL\"]\n        BES_RET[\"Return new_str\"]\n  end\n subgraph SG_FT_EXPAND[\"ft_expand token, data\"]\n    direction LR\n        EXP1_1[\"orig_value = (*token)-\u003evalue\"]\n        EXP1_2[\"exp_value = ft_build_expanded_string orig_value, data\"]\n        SG_BUILD_EXP_STR\n        EXP1_3[\"Free original value and assign expanded value to token\"]\n  end\n subgraph SG_APPLY[\"ft_apply\"]\n    direction LR\n        APP1{\"n_spl == 0?\"}\n        APP2[\"(*curr_tkn_ptr)-\u003evalue = \\\\\"]\n        APP3[\"Replace token with split tokens\"]\n  end\n subgraph SG_APPLY_IFS[\"ft_apply_ifs curr_tkn_ptr\"]\n    direction LR\n        IFS1[\"ft_pre_split curr_tkn_ptr (handles all-space)\"]\n        IFS_RET[\"Return curr unchanged\"]\n        IFS2[\"split_res = ft_split_string_by_whitespace (*curr_tkn_ptr)-\u003evalue, \u0026n_splited\"]\n        IFS3[\"ft_apply curr_tkn_ptr, split_res, n_splited\"]\n        SG_APPLY\n  end\n subgraph SG_PROCESS_EXPANDABLE[\"ft_process_expandable_token \u0026curr, data\"]\n    direction LR\n        PEX1[\"ft_expand \u0026curr, data\"]\n        SG_FT_EXPAND\n        PEX_WORD_CHECK[\"curr token is WORD and split_needed and value exists\"]\n        PEX_NO_SPLIT_CHECK{\"!data.no_split?\"}\n        PEX_APPLY_IFS[\"ft_apply_ifs \u0026curr\"]\n        SG_APPLY_IFS\n  end\n subgraph SG_EXPANDER[\"ft_expander token_head, data\"]\n    direction TB\n        EX1[\"curr = *token_head, prev = NULL, data.echo_pipe_flag = false\"]\n        EX_LOOP{\"while curr\"}\n        EX2[\"Reset data.herdoc based on prev\"]\n        EX3[\"ft_check_pipe_echo curr, data\"]\n        EX4[\"ft_c curr, data, prev – sets data.no_split\"]\n        EX_HEREDOC_CHECK{\"curr-\u003etype == TOKEN_REDIR_HEREDOC AND curr-\u003enext?\"}\n        EX_HANDLE_HEREDOC[\"ft_handle_heredoc_expansion_flags curr, data\"]\n        EX_EXPANDABLE_CHECK{\"ft_isexpandable curr\"}\n        EX_PROCESS_EXP[\"ft_process_expandable_token \u0026curr, data\"]\n        SG_PROCESS_EXPANDABLE\n  end\n    A[\"Start main\"] --\u003e A1{\"initialise shell (data, sh_vars, env)\"}\n    A1 -- Success --\u003e B[\"Loop: while true\"]\n    A1 -- Failure --\u003e Z_EXIT[\"Exit Shell status 1\"]\n    B --\u003e C{\"handle input prompt (data, sh_vars)\"}\n    C -- \"EOF/Ctrl-D\" --\u003e Z_EXIT_NORMAL[\"ft_tenv_clear, rl_clear_history, Exit Shell and clear\"]\n    C -- Empty Line --\u003e B\n    C -- Line Read --\u003e D[\"add_history sh_vars.line\"]\n    D --\u003e E{\"parse_and_expand data, sh_vars\"}\n    PE1 -- Syntax Error --\u003e PE_ERR1\n    PE1 -- No Syntax Error --\u003e PE2\n    PE2 -- Tokenization Fails/Empty --\u003e PE_ERR2\n    PE2 -- \"Token List Created sh_vars.tkn_list\" --\u003e PE3\n    PE3 --\u003e PE_OK\n    E -- Returns false --\u003e F_CLEANUP_LINE[\"Free sh_vars.line if exists\"]\n    F_CLEANUP_LINE --\u003e B\n    E -- Returns true --\u003e F[\"creat_excute_cleanup (data, sh_vars)\"]\n    EX1 --\u003e EX_LOOP\n    EX_LOOP -- Token Exists --\u003e EX2\n    EX2 --\u003e EX3\n    EX3 --\u003e EX4\n    EX4 --\u003e EX_HEREDOC_CHECK\n    EX_HEREDOC_CHECK -- Yes --\u003e EX_HANDLE_HEREDOC\n    EX_HEREDOC_CHECK -- No --\u003e EX_EXPANDABLE_CHECK\n    EX_EXPANDABLE_CHECK -- Yes --\u003e EX_PROCESS_EXP\n    EXP1_1 --\u003e EXP1_2\n    BES_SKIP_ESC_QUOTE -- Yes --\u003e BES_INC_I\n    BES_SKIP_ESC_QUOTE -- No --\u003e BES_PROC_EXP\n    PROCEXP1 --\u003e PROCEXP_QUOTE_HANDLE\n    PROCEXP_QUOTE_HANDLE -- No --\u003e PROCEXP_DOLLAR_CHECK\n    PROCEXP_DOLLAR_CHECK -- Yes --\u003e PROCEXP_HANDLE_DOLLAR\n    PROCEXP_HANDLE_DOLLAR --\u003e PROCEXP_END_ITER\n    PROCEXP_APPEND_LITERAL --\u003e PROCEXP_END_ITER\n    PROCEXP_UPDATE_QUOTE --\u003e PROCEXP_END_ITER\n    BES_PROC_EXP -- Success --\u003e BES_LOOP\n    BES_PROC_EXP -- Failure --\u003e BES_RET_NULL\n    BES_LOOP -- End of String --\u003e BES_RET\n    PEX_WORD_CHECK -- Yes --\u003e PEX_NO_SPLIT_CHECK\n    PEX_NO_SPLIT_CHECK -- Yes --\u003e PEX_APPLY_IFS\n    IFS1 -- Is all spaces/NULL --\u003e IFS_RET\n    IFS2 -- No split/Error --\u003e IFS_RET\n    IFS2 -- Split OK --\u003e IFS3\n    APP1 -- No --\u003e APP3\n    SG_EXPANDER --\u003e n1[\"End\"]\n\n    BES1@{ shape: rect}\n    PROCEXP_DOLLAR_CHECK@{ shape: diamond}\n\n```\n\n[Online Chart Of Parsing part](https://mermaid.live/edit#pako:eNqdWHtv4kgS_yq11mpeSx5AmJkgZeYIODcoHHBAdNkNo5YDDVjj2F53OzPZKNJ9h_uG90muqrtt3MYko-OfhO56_urRVTw6i2jJnbazCqLvi42XSJj15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bp7a35JxiKP0k8Q14Eb6dvm6W1mrLYsosL35Y6y3oXu1S0gqlekgr0WdEXBzwLx51Bbcthn5e5rPlL7wFE0leDPqjxWxyRtYrDTPk5bcNkgZowjrZNsZJuqraK0WVGYeqXtqlCMtEypC8K45-6CWmIc82vkTl49JOD2HgxbwONfk_7E29LuPS9uyhcIq1Tc9aJv3Ta1Mpqzh1P8FHHr84jyZk7csPv8HGhnzOWfOWlAXbiefiEbPik_BFFdxlnEqXrjdNWfbfmpOp3rZ7v4SC7JeE0u3ajNJRO--S4pWQ47Ufnh9M-qJ80Tw9PW6fN1nHrI_75gNcPeN5qHh_WG-9bjdbHDx9Pj983nmrOX0pv87BV_1B_f9I6rjdPT04_PP0PRgm9Mg)\n\n---\n\n## ⚡ Execution Engine\n\n### Command Dispatch System\n\nThe execution engine implements a sophisticated command classification and dispatch system:\n\n#### Command Type Classification:\n1. **Built-in Commands**: Internal shell commands\n2. **External Commands**: Programs in PATH or absolute paths\n3. **Pipeline Commands**: Multi-command pipe sequences\n4. **Redirection-only**: Pure I/O redirection without commands\n\n#### Execution Flow:\n```c\nint execute_commands(t_cmd *cmd_list, t_data *data)\n{\n    if (!cmd_list)\n        return (data-\u003elast_exit_status = 0);\n    \n    int cmd_count = count_commands(cmd_list, data);\n    \n    if (cmd_count == 1)\n        return handle_single_command(cmd_list, data);\n    else\n        return execute_pipeline(cmd_list, data);\n}\n```\n\n### Pipeline Implementation\n\n#### Pipeline Architecture:\n- **Process Chain**: Each command runs in separate process\n- **Pipe Management**: Automatic pipe creation and cleanup\n- **File Descriptor Handling**: Proper stdin/stdout redirection\n- **Error Propagation**: Correct exit status handling\n\n#### Pipeline Execution Algorithm:\n```c\nint execute_pipeline(t_cmd *cmd_list, t_data *data)\n{\n    t_pipeline_ctx ctx = {STDIN_FILENO, -1, {-1, -1}};\n    \n    // For each command in pipeline:\n    // 1. Create pipe if not last command\n    // 2. Fork child process\n    // 3. Setup file descriptors\n    // 4. Execute command\n    // 5. Close unused file descriptors\n    // 6. Wait for completion\n}\n```\n\n### Process Management\n\n#### Fork and Exec Pattern:\n```c\nvoid execute_child_process(t_cmd *cmd, t_data *data, char *path)\n{\n    // Child process setup:\n    set_signal_handlers_default();     // Reset signal handlers\n    apply_redirections(cmd);            // Setup I/O redirections\n    \n    char **env_array = convert_envlist_to_array(data-\u003eenv_list);\n    execve(path, cmd-\u003eargv, env_array); // Replace process image\n    \n    // Error handling if execve fails\n    handle_execve_error(path, cmd-\u003eargv[0], data);\n}\n```\n\n### I/O Redirection System\n\n#### Redirection Types:\n1. **Input Redirection** (`\u003c`): Redirect stdin from file\n2. **Output Redirection** (`\u003e`): Redirect stdout to file (truncate)\n3. **Append Redirection** (`\u003e\u003e`): Redirect stdout to file (append)\n4. **Here Document** (`\u003c\u003c`): Redirect stdin from inline text\n\n\n### Here Document Implementation\n\n#### Features:\n- **Delimiter Recognition**: Configurable end-of-input markers\n- **Variable Expansion**: Optional expansion based on delimiter quoting\n- **Multiple Heredocs**: Support for multiple heredocs per command\n- **Signal Handling**: Proper Ctrl-C handling during input\n\n#### Heredoc Processing:\n```c\nint process_heredocs(t_cmd *cmd_list, t_data *data)\n{\n    // 1. Count total heredocs\n    // 2. Process each heredoc sequentially\n    // 3. Create temporary file descriptors\n    // 4. Handle variable expansion\n    // 5. Store file descriptors for execution\n}\n```\n\n```mermaid\ngraph TD\n  A_MainLoop[main c Loop] --\u003e|t_cmd pointer cmd_list comma t_data pointer data| B_ExecCmds[execute commands]\n\n  subgraph execute commands [executor c execute commands]\n    B_ExecCmds --\u003e B1{cmd_list is null?}\n    B1 -- Yes --\u003e B_Ret0[data last exit status equals zero newline return zero]\n    B1 -- No --\u003e B2[Count commands in cmd list]\n    B2 --\u003e B3{command count equals one?}\n    B3 -- Yes Single Command --\u003e B4[handle single command]\n    B4 --\u003e B_UpdateStatusFromSingle[Update data last exit status from handle single command]\n    B_UpdateStatusFromSingle --\u003e B_RetStatus[return data last exit status]\n    B3 -- No Pipeline --\u003e B5{cmd list argv missing first argument?}\n    B5 -- Yes Error pipe starts with no command --\u003e B_SyntaxErrPipe[handle syntax error near pipe symbol]\n    B_SyntaxErrPipe --\u003e B_RetStatus\n    B5 -- No --\u003e B6[execute pipeline]\n    B6 --\u003e B_UpdateStatusFromPipe[Update data last exit status from execute pipeline]\n    B_UpdateStatusFromPipe --\u003e B_RetStatus\n  end\n\n  subgraph handle single command [executor c handle single command]\n    B4 --\u003e HS1{cmd node argv missing first argument?}\n    HS1 -- Yes --\u003e HS2{redirections exist?}\n    HS2 -- Yes Redirection Only --\u003e HS_ForkRedirOnly[Fork for redirection apply]\n    HS_ForkRedirOnly -- Child --\u003e HS_ApplyRedirChild[apply redirections] --\u003e HS_ExitChild[exit status from apply]\n    HS_ForkRedirOnly -- Parent --\u003e HS_WaitRedir[wait for redirection child] --\u003e HS_UpdateStatusRedir[update last exit status] --\u003e B_RetStatus\n    HS2 -- No --\u003e HS_SyntaxErr[handle syntax error invalid command] --\u003e B_RetStatus\n    HS1 -- No --\u003e HS3{is parent builtin cmd node?}\n    HS3 -- Yes --\u003e HS_ExecBuiltins[execute built ins] --\u003e B_RetStatus\n    HS3 -- No --\u003e HS_ExecExternal[execute external command] --\u003e B_RetStatus\n  end\n\n  subgraph execute external command [executor c execute external command]\n    HS_ExecExternal --\u003e EE1[determine executable path from command name and env list]\n    EE1 --\u003e EE2{executable path not found?}\n    EE2 -- Yes Not Found --\u003e EE_NotFound[print not found newline set exit status one two seven newline return one two seven]\n    EE2 -- No --\u003e EE3[fork new process]\n    EE3 --\u003e EE4{fork error?}\n    EE4 -- Yes Fork Error --\u003e EE_ForkErr[print fork error newline free path newline set exit status fail newline return fail]\n    EE4 -- No --\u003e EE5{in child process?}\n    EE5 -- Yes Child --\u003e EE_ChildStart[child process logic]\n    EE_ChildStart --\u003e EE_SetSigDefault[set default signal handlers]\n    EE_SetSigDefault --\u003e EE_ApplyRedir[apply redirections]\n    EE_ApplyRedir --\u003e EE_RedirFail{redirection failed?}\n    EE_RedirFail -- Yes --\u003e EE_ChildExitFail1[free path newline exit fail]\n    EE_RedirFail -- No --\u003e EE_ConvertEnv[convert env list to array]\n    EE_ConvertEnv --\u003e EE_EnvFail{env array allocation failed?}\n    EE_EnvFail -- Yes --\u003e EE_ChildExitFail2[free path newline exit fail]\n    EE_EnvFail -- No --\u003e EE_Execve[execute new program]\n    EE_Execve -- Error --\u003e EE_ExecveErr[print exec error newline free path newline free env array newline exit code one two six or fail]\n    EE5 -- No Parent --\u003e EE_ParentStart[parent process logic]\n    EE_ParentStart --\u003e EE_FreePathParent[free executable path]\n    EE_FreePathParent --\u003e EE_WaitParent[wait for child process]\n    EE_WaitParent --\u003e EE_UpdateStatusParent[update last exit status] --\u003e B_RetStatus\n  end\n\n  subgraph execute pipeline [pipeline c execute pipeline]\n    B6 --\u003e P1[initialize pipeline variables]\n    P1 --\u003e P2[command count equals count commands in list]\n    P2 --\u003e P3{command count equals zero?}\n    P3 -- Yes --\u003e P_RetSuccess[return success]\n    P3 -- No --\u003e P_LoopStart[loop while current command exists]\n    P_LoopStart --\u003e P4{next command exists and pipe creation failed?}\n    P4 -- Yes --\u003e P_PipeErr[print pipe error newline cleanup fds newline wait prior children newline return fail]\n    P4 -- No --\u003e P5[call fork and exec child]\n    P5 --\u003e P6{fork returned negative?}\n    P6 -- Yes --\u003e P_ForkErrLoop[cleanup fds newline wait prior children newline return fail]\n    P6 -- No --\u003e P7[record last child pid]\n    P7 --\u003e P8[handle parent side of pipe]\n    P8 --\u003e P9[advance to next command] --\u003e P_LoopStart\n    P_LoopStart -- End --\u003e P10{previous read end not standard input?}\n    P10 -- Yes --\u003e P_CloseLastRead[close previous read end] --\u003e P11\n    P10 -- No --\u003e P11\n    P11[wait for remaining children then update status] --\u003e B_UpdateStatusFromPipe\n  end\n\n  subgraph fork and exec child [pipeline c fork and exec child]\n    P5 --\u003e FE_Fork[create new process]\n    FE_Fork --\u003e FE_ForkErr{fork failed?}\n    FE_ForkErr -- Yes --\u003e FE_RetForkErr[print fork error newline return negative one]\n    FE_ForkErr -- No --\u003e FE_ChildCheck{in child process?}\n    FE_ChildCheck -- Yes --\u003e FE_SetupPipesChild[configure child pipes]\n    FE_SetupPipesChild --\u003e FE_ExecNodeChild[execute command node and exit]\n    FE_ChildCheck -- No --\u003e FE_SetSigParent[reset prompt signal handlers] --\u003e FE_RetPID[return child pid]\n  end\n\n  subgraph execute command node [pipeline c and executor utils execute command node]\n    FE_ExecNodeChild --\u003e ECN1[reset default signal handlers]\n    ECN1 --\u003e ECN2[apply redirections]\n    ECN2 --\u003e ECN_RedirFail{redirection failed?}\n    ECN_RedirFail -- Yes --\u003e ECN_ExitFail1[exit fail]\n    ECN_RedirFail -- No --\u003e ECN3{cmd node missing argv or first arg?}\n    ECN3 -- Yes --\u003e ECN_InvalidNode[print error newline exit fail]\n    ECN3 -- No --\u003e ECN4[attempt built in execution]\n    ECN4 --\u003e ECN5{built in handled?}\n    ECN5 -- Yes --\u003e ECN_ExitBuiltin[exit with built in status]\n    ECN5 -- No --\u003e ECN6[convert env list to array]\n    ECN6 --\u003e ECN_EnvFail{env conversion failed?}\n    ECN_EnvFail -- Yes --\u003e ECN_ExitFail2[exit fail]\n    ECN_EnvFail -- No --\u003e ECN7[find command path]\n    ECN7 --\u003e ECN_CheckPath{path invalid?}\n    ECN_CheckPath -- Yes --\u003e ECN_ExitFail3[print not found newline exit fail]\n    ECN_CheckPath -- No --\u003e ECN8[exec new program]\n    ECN8 -- Error --\u003e ECN_ExecveErr[print exec error newline exit appropriate code]\n  end\n\n  subgraph execute built ins [execute builtin c execute built ins]\n    HS_ExecBuiltins --\u003e BI0{cmd node valid?}\n    BI0 -- No --\u003e BI_RetFail[return negative one]\n    BI0 -- Yes --\u003e BI1{is exit built in?}\n    BI1 -- Yes --\u003e BI_Exit[call exit built in] --\u003e B_RetStatus\n    BI1 -- No --\u003e BI2{is cd built in?}\n    BI2 -- Yes --\u003e BI_CD[call cd built in] --\u003e B_RetStatus\n    BI2 -- No --\u003e BI3{is unset built in?}\n    BI3 -- Yes --\u003e BI_Unset[call unset built in] --\u003e B_RetStatus\n    BI3 -- No --\u003e BI4{export built in with arguments?}\n    BI4 -- Yes --\u003e BI_ExportArgs[call export built in with args] --\u003e B_RetStatus\n    BI4 -- No --\u003e BI5{is one of pwd echo env or export no args?}\n    BI5 -- Yes --\u003e BI_SaveFD[save original file descriptors]\n    BI_SaveFD --\u003e BI_FDError1{save failed?}\n    BI_FDError1 -- Yes --\u003e BI_RetFail\n    BI_FDError1 -- No --\u003e BI_ApplyRedir[apply redirections]\n    BI_ApplyRedir --\u003e BI_RedirError{redir failed?}\n    BI_RedirError -- Yes --\u003e BI_SetFailStatus[set data last exit status fail newline builtin status fail] --\u003e BI_RestoreFD[restore saved file descriptors]\n    BI_RedirError -- No --\u003e BI_DispatchIO{which built in to run}\n    BI_DispatchIO -- Yes pwd --\u003e BI_Pwd[call pwd built in] --\u003e BI_StoreStatus\n    BI_DispatchIO -- Yes echo --\u003e BI_Echo[call echo built in] --\u003e BI_StoreStatus\n    BI_DispatchIO -- Yes env --\u003e BI_Env[call env built in] --\u003e BI_StoreStatus\n    BI_DispatchIO -- Yes export no args --\u003e BI_ExportNoArgs[display export list] --\u003e BI_StoreStatus\n    BI_StoreStatus --\u003e BI_RestoreFD --\u003e BI_FDError2{restore failed?}\n    BI_FDError2 -- Yes --\u003e BI_RetFail\n    BI_FDError2 -- No --\u003e BI_RetBuiltinStatus[return builtin status]\n    BI5 -- No --\u003e BI_RetFail\n  end\n\n  subgraph apply redirections [redirections c apply redirections]\n    ECN2 --\u003e AR1{no redirections?}\n    AR1 -- Yes --\u003e AR_RetSuccess[return zero]\n    AR1 -- No --\u003e AR_LoopStart[loop through each redirection]\n    AR_LoopStart --\u003e AR2{type of redirection}\n    AR2 -- infile redirect --\u003e AR_In[handle infile redirect] --\u003e AR_StatusCheck\n    AR2 -- heredoc redirect --\u003e AR_HD[handle heredoc redirect] --\u003e AR_StatusCheck\n    AR2 -- outfile truncate --\u003e AR_Out[handle outfile truncate redirect] --\u003e AR_StatusCheck\n    AR2 -- outfile append --\u003e AR_App[handle outfile append redirect] --\u003e AR_StatusCheck\n    AR_StatusCheck -- Yes failed --\u003e AR_RetFail[return fail]\n    AR_StatusCheck -- No --\u003e AR_Next[advance to next redirection] --\u003e AR_LoopStart\n    AR_LoopStart -- End --\u003e AR_RetSuccess\n  end\n\n\n```\n\n\n[Online Chart Of Execution part](https://mermaid.live/edit#pako:eNqtWltv2zgW_iuEn9sikmXHzcMOUsdBA8ymRrKDxaxiGKpE28TIlJaSnKSa_vc9vJO6xJnB9qGQqO9ceW6k007SIsOTq8meJeUB_evmiSJ0vf1nQuivRVHGR3hAKeLPG_Tx4z_-rLfpMUNlQWiNGYLnbU6qGqXF8ZigepsldWK-8pc_0Zft6gWny2NWxRgemhpLNM2qzRPl8qrmuxTf_Y4URQGS0AAxgn-WPdcPfQlaoxSpEG3y_JefChkAAv2OFXD7gOuLWCicJ4DGL6RGVZ3UTYXwf5skr9APzApE8XNOKEYM1w2jYm3jMrwvJL8wXhYNra3y3HPgK66KJggldNoqEIA5iRJXUGx0nWpdHwnd5xgtFYGgj-IDPMNqJT8qblpKpAz8rQTr8KMw6ZYVR8kqlsto2PId4NCb3EfYWqfKL7Hy16CYjWslOHBNSiycLJjMWu03lLD9CR1JxVVBO8LkUnPEtDaummlXrRiDSCmBFxfD6go9k_qAaKFNUDo-vtI6eQE0F2tcKRYRFjwoTjSj1-P3Ije2e6Rdk119dFTMTdCXykbNaz6yS0Kp83s0xnaQ35CmmGad9Bvcdi8H3xF2Xx9FBoLXM_ye7QO8m5ZfH8OW4YwwnNakoBU3vHLAoQY_WBD6RvNXRb29Ldgf4htfjPkb2oHuDk-UlGX-utEcfQrOfnkgeab5XXOw-CyWY0Hssqs2GrqCPZKg3m6dE7lOGPhEM_p3QmrxOX6Gp57-KZdhpLr7LYkaGTy9pBuOV-VTFbDA0MT4YGoQekpykpnNH2MaeEynLRTjUhr5vSF5rYoj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NqEhK_V2LvqP6KN4BbDRC7oYYSjyGBwzQIu1x_HqjOXYRZ1kWTS10qCHhUz6QKPy3ptY8e5C_zBx2GqtLAUBDfe2yVoD3MHbXdATIrHACwZ1dnFGvT20D4h6_1L17DzcSepEzGBrm9sOLSJMjkw-TPSPZ5AqciT9MjpgdE_46aTnkaVIf8BE_Ta7gUR3ZniZP9CeQlQn9T1EcNaUI18nVLskreJM3Fzck4TOqgYBEzMQfOkyuLgPBYnLVTl4mVx9nl_NP4eco-hzNw8Xni3n4YfI6uQoup58uFjN4_7wIozBYLH5-mPwQUsNP8yCaR1G4iIJZMJ8uop__AysSfdE)\n\n---\n\n## 🔨 Built-in Commands\n\n### 🔧 Built-in Commands Portfolio\n\n| Command | Description | Options/Args | Special Features |\n|---------|-------------|--------------|------------------|\n| `echo` | Display text | `-n` flag | Variable expansion support |\n| `cd` | Change directory | Relative/absolute paths | HOME directory handling |\n| `pwd` | Print working directory | None | Always shows absolute path |\n| `export` | Export variables | Variable assignments | Environment modification |\n| `unset` | Remove variables | Variable names | Safe environment cleanup |\n| `env` | Display environment | None | Complete environment listing |\n| `exit` | Terminate shell | Optional exit code | Cleanup and graceful exit |\n\n---\n\n\n### Command Implementation Details\n\n### Built-in Command Features\n\n#### Advanced `export` Features:\n- **Append Mode**: `export VAR+=value` appends to existing variable\n- **Identifier Validation**: Ensures valid variable names\n- **Display Mode**: Shows all exported variables in sorted order\n\n#### `cd` Special Cases:\n- **Home Directory**: `cd` or `cd ~` goes to $HOME\n- **Previous Directory**: `cd -` goes to $OLDPWD\n- **Tilde Expansion**: `cd ~/Documents` expands tilde\n- **Environment Updates**: Automatically updates PWD and OLDPWD\n\n---\n\n## 📡 Signal Handling\n\n### Signal Architecture\n\nThe shell implements context-aware signal handling with different behaviors for different execution contexts:\n\n#### Signal Contexts:\n1. **Prompt Context**: Waiting for user input\n2. **Execution Context**: Running commands\n3. **Heredoc Context**: Processing here documents\n4. **Pipeline Context**: Executing command pipelines\n\n### Signal Handler Implementation\n\n#### Prompt Signal Handler:\n```c\nvoid sigint_handler_prompt(int signum)\n{\n    (void)signum;\n    \n    // Display new prompt on new line\n    printf(\"\\n\");\n    rl_on_new_line();           // Notify readline of new line\n    rl_replace_line(\"\", 0);     // Clear current line\n    rl_redisplay();             // Redisplay prompt\n}\n```\n\n#### Heredoc Signal Handler:\n```c\nvoid sigint_handler_heredoc(int signum)\n{\n    (void)signum;\n    \n    // Set global flag for heredoc interruption\n    g_signal_received = SIGINT;\n    \n    // Close heredoc input\n    close(STDIN_FILENO);\n}\n```\n\n### Signal Management System\n\n#### Signal Handler Setup:\n```c\nvoid set_signal_handlers_prompt(void)\n{\n    struct sigaction sa_int, sa_quit;\n    \n    // SIGINT (Ctrl-C) handler\n    sa_int.sa_handler = sigint_handler_prompt;\n    sigemptyset(\u0026sa_int.sa_mask);\n    sa_int.sa_flags = SA_RESTART;\n    sigaction(SIGINT, \u0026sa_int, NULL);\n    \n    // SIGQUIT (Ctrl-\\) - ignore in interactive mode\n    sa_quit.sa_handler = SIG_IGN;\n    sigemptyset(\u0026sa_quit.sa_mask);\n    sa_quit.sa_flags = 0;\n    sigaction(SIGQUIT, \u0026sa_quit, NULL);\n}\n```\n\n#### Context-Aware Signal Switching:\n- **Prompt → Execution**: Switch to default handlers before fork\n- **Execution → Prompt**: Restore custom handlers after wait\n- **Heredoc Entry**: Install heredoc-specific handlers\n- **Heredoc Exit**: Restore previous handlers\n\n---\n\n#### Exit Code Standards:\n- **0**: Success\n- **1**: General error\n- **2** or **258** : Misuse of shell built-ins\n- **126**: Command found but not executable\n- **127**: Command not found\n- **128+n**: Fatal error signal \"n\"\n\n---\n\n*Developed with ❤️ at 42 School - Where code meets creativity*\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fyomazini%2F42cursus-minishell","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fyomazini%2F42cursus-minishell","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fyomazini%2F42cursus-minishell/lists"}