The user wants me to build a simple Unix shell in C that supports pipes and redirection. This is a classic systems programming project that requires understanding of:
Process creation (fork)
Program execution (exec)
Inter-process communication (pipes)
File redirection (dup2)
Signal handling
Command parsing
I'll create a comprehensive shell implementation with:
Basic command execution
Pipes (|)
Input redirection (<)
Output redirection (>)
Append redirection (>>)
Built-in commands (cd, exit, pwd)
Signal handling (Ctrl+C)
Proper error handling
Let me write clean, well-documented code that can be compiled on any Unix-like system.
Simple Unix Shell in C
I'll create a functional Unix shell that supports pipes, redirection, and built-in commands.
shell.c
c
/*
* Simple Unix Shell
* Supports: pipes (|), input redirection (<), output redirection (>), append (>>)
* Built-ins: cd, exit, pwd
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <ctype.h>
#include <signal.h>
#define MAX_LINE 1024
#define MAX_ARGS 64
#define MAX_PIPES 16
// Command structure
typedef struct {
char *args[MAX_ARGS];
int argc;
char *input_file;
char *output_file;
int append_output;
} Command;
// Global for signal handling
pid_t current_pid = -1;
// Function prototypes
void sigint_handler(int sig);
void print_prompt(void);
char *read_line(void);
char **parse_commands(char *line, int *num_cmds);
int parse_single_command(char *cmd_str, Command *cmd);
void free_commands(char **commands, int num_cmds);
void execute_command(Command *cmd, int pipe_in, int pipe_out, int is_last);
void execute_pipeline(char **commands, int num_cmds);
int handle_builtin(Command *cmd);
void trim_whitespace(char *str);
// Signal handler for Ctrl+C
void sigint_handler(int sig) {
(void)sig;
printf("\n");
print_prompt();
fflush(stdout);
}
// Print shell prompt
void print_prompt(void) {
char cwd[MAX_LINE];
if (getcwd(cwd, sizeof(cwd)) != NULL) {
printf("\033[1;32m%s\033[0m$ ", cwd); // Green prompt with current directory
} else {
printf("$ ");
}
fflush(stdout);
}
// Read a line from stdin
char *read_line(void) {
char *line = malloc(MAX_LINE);
if (!line) {
perror("malloc");
exit(EXIT_FAILURE);
}
if (fgets(line, MAX_LINE, stdin) == NULL) {
free(line);
return NULL; // EOF
}
// Remove trailing newline
size_t len = strlen(line);
if (len > 0 && line[len-1] == '\n') {
line[len-1] = '\0';
}
return line;
}
// Trim leading and trailing whitespace
void trim_whitespace(char *str) {
char *end;
// Trim leading space
while (isspace((unsigned char)*str)) {
str++;
}
if (*str == 0) { // All spaces
return;
}
// Trim trailing space
end = str + strlen(str) - 1;
while (end > str && isspace((unsigned char)*end)) {
end--;
}
end[1] = '\0';
}
// Parse commands separated by pipes
char **parse_commands(char *line, int *num_cmds) {
char **commands = malloc(MAX_PIPES * sizeof(char*));
if (!commands) {
perror("malloc");
exit(EXIT_FAILURE);
}
*num_cmds = 0;
char *token = strtok(line, "|");
while (token != NULL && *num_cmds < MAX_PIPES) {
trim_whitespace(token);
commands[*num_cmds] = strdup(token);
(*num_cmds)++;
token = strtok(NULL, "|");
}
return commands;
}
// Parse a single command (handles redirection)
int parse_single_command(char *cmd_str, Command *cmd) {
cmd->argc = 0;
cmd->input_file = NULL;
cmd->output_file = NULL;
cmd->append_output = 0;
char *token;
char *saveptr;
char *str = strdup(cmd_str);
if (!str) {
perror("strdup");
return -1;
}
token = strtok_r(str, " \t", &saveptr);
while (token != NULL && cmd->argc < MAX_ARGS - 1) {
if (strcmp(token, "<") == 0) {
// Input redirection
token = strtok_r(NULL, " \t", &saveptr);
if (token) {
cmd->input_file = strdup(token);
}
} else if (strcmp(token, ">") == 0) {
// Output redirection (truncate)
token = strtok_r(NULL, " \t", &saveptr);
if (token) {
cmd->output_file = strdup(token);
cmd->append_output = 0;
}
} else if (strcmp(token, ">>") == 0) {
// Output redirection (append)
token = strtok_r(NULL, " \t", &saveptr);
if (token) {
cmd->output_file = strdup(token);
cmd->append_output = 1;
}
} else {
// Regular argument
cmd->args[cmd->argc++] = strdup(token);
}
token = strtok_r(NULL, " \t", &saveptr);
}
cmd->args[cmd->argc] = NULL; // NULL-terminate for execvp
free(str);
return 0;
}
// Free parsed commands
void free_commands(char **commands, int num_cmds) {
for (int i = 0; i < num_cmds; i++) {
free(commands[i]);
}
free(commands);
}
// Free a single command structure
void free_command(Command *cmd) {
for (int i = 0; i < cmd->argc; i++) {
free(cmd->args[i]);
}
if (cmd->input_file) free(cmd->input_file);
if (cmd->output_file) free(cmd->output_file);
}
// Handle built-in commands (cd, exit, pwd)
int handle_builtin(Command *cmd) {
if (cmd->argc == 0) return 0;
// cd command
if (strcmp(cmd->args[0], "cd") == 0) {
char *dir = cmd->args[1];
if (dir == NULL) {
dir = getenv("HOME");
if (dir == NULL) {
fprintf(stderr, "cd: HOME not set\n");
return 1;
}
}
if (chdir(dir) != 0) {
perror("cd");
return 1;
}
return 1;
}
// exit command
if (strcmp(cmd->args[0], "exit") == 0) {
int status = 0;
if (cmd->args[1]) {
status = atoi(cmd->args[1]);
}
exit(status);
}
// pwd command
if (strcmp(cmd->args[0], "pwd") == 0) {
char cwd[MAX_LINE];
if (getcwd(cwd, sizeof(cwd)) != NULL) {
printf("%s\n", cwd);
} else {
perror("pwd");
return 1;
}
return 1;
}
// export command (set environment variable)
if (strcmp(cmd->args[0], "export") == 0) {
if (cmd->args[1]) {
char *eq = strchr(cmd->args[1], '=');
if (eq) {
*eq = '\0';
setenv(cmd->args[1], eq + 1, 1);
}
}
return 1;
}
return 0; // Not a built-in
}
// Execute a single command with redirections
void execute_command(Command *cmd, int pipe_in, int pipe_out, int is_last) {
if (cmd->argc == 0) return;
// Check for built-ins first (only if single command)
if (pipe_in == -1 && pipe_out == -1) {
if (handle_builtin(cmd)) {
return;
}
}
pid_t pid = fork();
if (pid < 0) {
perror("fork");
return;
}
if (pid == 0) { // Child process
// Handle input redirection
if (cmd->input_file) {
int fd = open(cmd->input_file, O_RDONLY);
if (fd < 0) {
perror("open input");
exit(EXIT_FAILURE);
}
dup2(fd, STDIN_FILENO);
close(fd);
} else if (pipe_in != -1) {
dup2(pipe_in, STDIN_FILENO);
}
// Handle output redirection
if (cmd->output_file) {
int flags = O_WRONLY | O_CREAT;
flags |= cmd->append_output ? O_APPEND : O_TRUNC;
int fd = open(cmd->output_file, flags, 0644);
if (fd < 0) {
perror("open output");
exit(EXIT_FAILURE);
}
dup2(fd, STDOUT_FILENO);
close(fd);
} else if (pipe_out != -1) {
dup2(pipe_out, STDOUT_FILENO);
}
// Close pipe file descriptors in child
if (pipe_in != -1) close(pipe_in);
if (pipe_out != -1) close(pipe_out);
// Execute the command
execvp(cmd->args[0], cmd->args);
perror("execvp");
exit(EXIT_FAILURE);
}
// Parent process
current_pid = pid;
}
// Execute a pipeline of commands
void execute_pipeline(char **commands, int num_cmds) {
int prev_pipe = -1;
int pipefd[2];
pid_t pids[MAX_PIPES];
for (int i = 0; i < num_cmds; i++) {
Command cmd;
if (parse_single_command(commands[i], &cmd) < 0) {
continue;
}
if (cmd.argc == 0) {
free_command(&cmd);
continue;
}
// Check if this is the last command
int is_last = (i == num_cmds - 1);
// Create pipe for all but the last command
int curr_pipe = -1;
if (!is_last) {
if (pipe(pipefd) < 0) {
perror("pipe");
free_command(&cmd);
return;
}
curr_pipe = pipefd[1]; // Write end
}
// Handle built-in commands (only if single command)
if (num_cmds == 1 && handle_builtin(&cmd)) {
free_command(&cmd);
continue;
}
pid_t pid = fork();
if (pid < 0) {
perror("fork");
free_command(&cmd);
return;
}
if (pid == 0) { // Child process
// Handle input
if (cmd.input_file) {
int fd = open(cmd.input_file, O_RDONLY);
if (fd < 0) {
perror("open input");
exit(EXIT_FAILURE);
}
dup2(fd, STDIN_FILENO);
close(fd);
} else if (prev_pipe != -1) {
dup2(prev_pipe, STDIN_FILENO);
}
// Handle output
if (cmd.output_file) {
int flags = O_WRONLY | O_CREAT;
flags |= cmd.append_output ? O_APPEND : O_TRUNC;
int fd = open(cmd.output_file, flags, 0644);
if (fd < 0) {
perror("open output");
exit(EXIT_FAILURE);
}
dup2(fd, STDOUT_FILENO);
close(fd);
} else if (curr_pipe != -1) {
dup2(curr_pipe, STDOUT_FILENO);
}
// Close all pipe fds
if (prev_pipe != -1) close(prev_pipe);
if (curr_pipe != -1) close(curr_pipe);
if (!is_last) {
close(pipefd[0]);
close(pipefd[1]);
}
execvp(cmd.args[0], cmd.args);
fprintf(stderr, "%s: command not found\n", cmd.args[0]);
exit(EXIT_FAILURE);
}
// Parent process
pids[i] = pid;
current_pid = pid;
// Close previous pipe read end
if (prev_pipe != -1) {
close(prev_pipe);
}
// Close current pipe write end
if (curr_pipe != -1) {
close(curr_pipe);
}
// Set up for next iteration
if (!is_last) {
prev_pipe = pipefd[0]; // Read end becomes input for next command
}
free_command(&cmd);
}
// Wait for all children
for (int i = 0; i < num_cmds; i++) {
int status;
waitpid(pids[i], &status, 0);
}
current_pid = -1;
}
int main(void) {
char *line;
char **commands;
int num_cmds;
// Set up signal handler
signal(SIGINT, sigint_handler);
signal(SIGTSTP, SIG_IGN); // Ignore Ctrl+Z
printf("\033[1;34m=========================================\033[0m\n");
printf("\033[1;34m Simple Unix Shell - pipes & redirects \033[0m\n");
printf("\033[1;34m=========================================\033[0m\n");
printf("Supports: | (pipe), < (input), > (output), >> (append)\n");
printf("Built-ins: cd, pwd, exit, export\n\n");
while (1) {
print_prompt();
line = read_line();
if (line == NULL) {
printf("\nGoodbye!\n");
break; // EOF (Ctrl+D)
}
// Skip empty lines
trim_whitespace(line);
if (strlen(line) == 0) {
free(line);
continue;
}
// Parse commands separated by pipes
commands = parse_commands(line, &num_cmds);
if (num_cmds > 0) {
execute_pipeline(commands, num_cmds);
}
free_commands(commands, num_cmds);
free(line);
}
return 0;
}
This shell demonstrates core Unix concepts including process forking, pipe creation, file descriptor manipulation, and signal handling. It's a great learning tool for understanding how real shells like bash work internally!