Skip to content
Snippets Groups Projects
Select Git revision
  • 7c5c6dba29da900f067a9b185fd2a6520b74b333
  • main default
2 results

README.md

Blame
  • questions.md 4.57 KiB
    1. Your shell forks multiple child processes when executing piped commands. How does your implementation ensure that all child processes complete before the shell continues accepting user input? What would happen if you forgot to call waitpid() on all child processes?

    answer here

    The parent process in execute_pipeline ensures all child processes complete before resuming with:

    for (int i = 0; i < num_cmds; i++) {
        waitpid(pids[i], NULL, 0); // Wait for all children
    }

    Consequences of skipping waitpid():

    Zombie processes: Child processes remain in the process table, leaking resources.

    I/O corruption: The shell prompt may print before child outputs finish, e.g., running sleep 2 | echo "hello" would show the prompt immediately, while hello appears later, overlapping with user input.

    1. The dup2() function is used to redirect input and output file descriptors. Explain why it is necessary to close unused pipe ends after calling dup2(). What could go wrong if you leave pipes open?

    answer here

    After dup2(), unused pipe ends are closed in child processes:

    if (i > 0) {
        dup2(prev_pipe, STDIN_FILENO);
        close(prev_pipe); // Close original FD after redirection
    }

    Why this is critical:

    Resource leaks: Unclosed file descriptors (FDs) count toward the system-wide FD limit (e.g., 1024).

    Deadlocks: Open write FDs prevent readers from detecting EOF. For example, if a parent doesn’t close its write FD, the child process reading from the pipe will block indefinitely.

    1. Your shell recognizes built-in commands (cd, exit, dragon). Unlike external commands, built-in commands do not require execvp(). Why is cd implemented as a built-in rather than an external command? What challenges would arise if cd were implemented as an external process?

    answer here

    Process isolation: External commands run in child processes; their directory changes don’t propagate to the parent shell.

    Challenges for external cd:

    No effect: The shell’s working directory remains unchanged, making cd functionally useless.

    Workarounds: Would require complex IPC (e.g., signaling or shared memory) to sync directories, adding significant overhead.