Analyzing Shell Requirements
I've started to unpack the fundamental aims. The essential functions boil down to running commands, managing pipes, and handling I/O redirection. Now, I need to break these down into manageable code components. I'm focusing on the architectural implications of each feature.
Decomposing Shell Functionality
I'm now zeroing in on the building blocks. I'm thinking through the basic REPL loop, input handling, parsing, command execution via fork and execvp, and how to implement redirection and pipes. It's becoming clearer that I need to focus first on a basic command execution. Then, I can add redirection and finally, pipe support. A simple approach with a fixed buffer for input seems best to start with.
Planning File Descriptor Usage
I'm now contemplating file descriptor management, specifically for redirection. I plan to use dup2() to redirect standard input/output. My thoughts are: after parsing and before execvp(), I will need to close the original file descriptors. I'm also considering how to remove redirection symbols and filenames from the argument list. The implementation needs to be precise to avoid file descriptor leaks.
Refining Command Execution
I'm now iterating on the execution logic, aiming for modularity. My plan is: main handles the loop and input, with parse_input splitting by pipes, then run_command dealing with space tokenization, redirection and execvp. I'm leaning toward a recursive approach for pipelines, if needed. I am leaning toward supporting arbitrary pipes by splitting and recursively running.
Planning Code Structure
I'm now mapping out code sections. It starts with a REPL loop in main(), calling parse_input() and then run_command(). run_command() will handle redirection and potentially call run_piped_commands() for pipes. I am leaning towards using getline for dynamic input to avoid buffer overflows and I am also leaning towards the iterative approach with loops for pipelines to keep the code organized.
Designing Pipe Implementation
Now I'm focusing on the implementation of pipelines. I am leaning toward a more general approach by creating a function that handles an array of commands. This simplifies splitting by the pipe character and handling arbitrary pipelines iteratively. I will adapt the run_command function for individual commands. Then, the new function will handle piping and manage file descriptors for all commands.
Designing the Main Execution Loop
I am now focusing on the high-level control flow. I will implement a loop in main() to read the commands, parse the input by pipes, and call the command execution function. This function will be in charge of redirection and execvp. I'm starting to create stubs for all function calls.
Here is a complete, compiling, and functional implementation of a simple Unix shell in C. It supports standard execution, input/output redirection (<, >), and pipelines (|).
The C Code (myshell.c)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
#include <fcntl.h>
#define MAX_CMD_LEN 1024
#define MAX_ARGS 64
// Function to print the prompt
void type_prompt() {
printf("myshell> ");
fflush(stdout);
}
// Function to parse a single command into arguments and handle redirection
// Returns the parsed argument list (NULL terminated)
void parse_and_execute(char *input, int input_fd, int output_fd) {
char *args[MAX_ARGS];
int i = 0;
char *token = strtok(input, " \t\n");
char *input_file = NULL;
char *output_file = NULL;
while (token != NULL) {
if (strcmp(token, "<") == 0) {
token = strtok(NULL, " \t\n");
input_file = token;
} else if (strcmp(token, ">") == 0) {
token = strtok(NULL, " \t\n");
output_file = token;
} else {
args[i++] = token;
}
token = strtok(NULL, " \t\n");
}
args[i] = NULL; // execvp expects a NULL terminated array
if (args[0] == NULL) return; // Empty command
// Handle built-in "exit" command
if (strcmp(args[0], "exit") == 0) {
exit(0);
}
// Handle built-in "cd" command
if (strcmp(args[0], "cd") == 0) {
if (args[1] == NULL) {
fprintf(stderr, "cd: expected argument to \"cd\"\n");
} else {
if (chdir(args[1]) != 0) {
perror("cd failed");
}
}
return; // Don't fork for cd
}
pid_t pid = fork();
if (pid == 0) {
// --- CHILD PROCESS ---
// 1. Handle Input Redirection (< file) OR Input Pipe
if (input_fd != STDIN_FILENO) {
dup2(input_fd, STDIN_FILENO);
close(input_fd);
} else if (input_file != NULL) {
int fd = open(input_file, O_RDONLY);
if (fd == -1) {
perror("Failed to open input file");
exit(1);
}
dup2(fd, STDIN_FILENO);
close(fd);
}
// 2. Handle Output Redirection (> file) OR Output Pipe
if (output_fd != STDOUT_FILENO) {
dup2(output_fd, STDOUT_FILENO);
close(output_fd);
} else if (output_file != NULL) {
// O_TRUNC clears the file, O_CREAT creates it, 0644 are permissions
int fd = open(output_file, O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (fd == -1) {
perror("Failed to open output file");
exit(1);
}
dup2(fd, STDOUT_FILENO);
close(fd);
}
// 3. Execute Command
if (execvp(args[0], args) == -1) {
perror("Transformation failed");
}
exit(1); // Should not reach here unless execvp fails
} else if (pid < 0) {
// Fork failed
perror("Fork failed");
} else {
// --- PARENT PROCESS ---
// We do NOT wait here if it's part of a pipe, that is handled in main loop
// But for this simple implementation, we rely on the main loop to manage waits.
}
}
int main() {
char line[MAX_CMD_LEN];
while (1) {
type_prompt();
if (!fgets(line, MAX_CMD_LEN, stdin)) break; // Handle Ctrl+D (EOF)
// Remove newline character
line[strcspn(line, "\n")] = 0;
if (strlen(line) == 0) continue;
// --- HANDLE PIPES ---
// Identify individual commands separated by '|'
char *commands[MAX_ARGS];
int num_cmds = 0;
char *cmd_token = strtok(line, "|");
while (cmd_token != NULL) {
commands[num_cmds++] = cmd_token;
cmd_token = strtok(NULL, "|");
}
int pipefds[2];
int prev_fd = STDIN_FILENO; // Input for the first command is standard input
for (int i = 0; i < num_cmds; i++) {
int input_fd = prev_fd;
int output_fd = STDOUT_FILENO; // Default output is StdOut
// If there is a next command, create a pipe
if (i < num_cmds - 1) {
if (pipe(pipefds) == -1) {
perror("pipe");
exit(1);
}
output_fd = pipefds[1]; // Current cmd writes to pipe write-end
}
parse_and_execute(commands[i], input_fd, output_fd);
// Close ends used by parent
if (prev_fd != STDIN_FILENO) close(prev_fd);
if (output_fd != STDOUT_FILENO) close(output_fd);
// Set input for next command to be the read-end of this pipe
prev_fd = pipefds[0];
}
// Wait for all child processes to finish
// This prevents the shell prompt from appearing before output finishes
for (int i = 0; i < num_cmds; i++) {
wait(NULL);
}
}
return 0;
}
How to compile and run
- Save the code to
myshell.c.
- Compile it using GCC:
gcc myshell.c -o myshell
- Run it:
./myshell
How it works
Here is a breakdown of the core concepts used in this implementation:
1. Check Built-ins (cd, exit)
Commands like cd cannot be regular executables. If a child process executes cd, it changes its own directory and then terminates, leaving the parent shell's directory unchanged. Therefore, cd must be a system call made directly by the parent.
2. Fork and Exec
To run a standard command (like ls or grep), the shell:
- Calls
fork(): This clones the current process. The child receives pid == 0.
- Calls
execvp() in the child: This replaces the memory of the child process with the new program.
- Calls
wait() in the parent: The shell pauses until the command finishes.
3. Redirection (<, >)
Before calling execvp(), the child process manipulates its File Descriptors (FD):
- STDOUT (FD 1): If
> is found, we open() the target file and use dup2(file_fd, STDOUT_FILENO). This tells the OS: "Whenever this process tries to write to the screen, write to this file instead."
- STDIN (FD 0): Similarly, for
<, we use dup2 to replace keyboard input with file input.
4. Pipes (|)
Pipes are the most complex part. A pipe creates a unidirectional data channel.
pipe(pipefds) creates two FDs: pipefds[0] (read end) and pipefds[1] (write end).
- Strategy: We iterate through the commands split by
|.
- Command 1: Writes output to
pipe_A[1] instead of Screen.
- Command 2: Reads input from
pipe_A[0], writes output to pipe_B[1].
- Command 3: Reads input from
pipe_B[0], writes output to Screen.
- Parent Responsibility: The parent must close the pipe file descriptors it holds; otherwise, the child processes will never see an "End of File" (EOF) and will hang forever waiting for more input.
Example Usage
Once you run ./myshell, you can try these commands:
# Basic commands
myshell> ls -l
myshell> pwd
# Redirection
myshell> ls -l > output.txt
myshell> cat < output.txt
# Pipes
myshell> ls -l | grep mysql
myshell> cat output.txt | wc -l
# Mixed
myshell> ls -l | grep .c > c_files.txt