Refining Scope Definition
I'm now zeroing in on defining the precise scope. Realizing a fully production-ready shell like bash is too ambitious initially. The core will have essential scripting, adhering to POSIX standards. Further exploring the trade-offs between simplicity and functionality will inform future decisions. My current aim is for a focused MVP, not a complete replacement.
Pinpointing the MVP Core
I've decided to concentrate on a functional core for my shell, adhering to POSIX concepts in C. It'll implement a Read-Eval-Print Loop, parsing, fork() and execvp() execution, built-in commands like cd and exit, scripting support, and environment variable handling. This approach directly maps the concepts to system calls, aligning with the initial learning and demonstration goal. The focus now is on a basic but working shell.
Constructing Core Functionality
I'm now thinking about the shell's heart: executing commands, whether interactive or from scripts. The reader will use getline for its simplicity, while the parser uses strtok. Execution will differentiate built-in commands like cd (using chdir()) and exit (calling exit()), from external programs, requiring fork() and execvp(). Scripting will loop using feof on a FILE*, opening a script if given, otherwise using stdin. Initial includes will be stdio.h, stdlib.h, unistd.h, sys/wait.h, and string.h.
Building Basic Execution Logic
I'm presently building the shell's execution capabilities. This includes fork, execvp, and waitpid for launching processes. For scripting, main will check argc; if a file is supplied, freopen it to stdin. This is to make my life easier. I'm prioritizing the core structure and functionality, adhering to a "POSIX-compliance" flavor within the given constraints. The flow remains main -> loop -> read -> parse -> execute. I'm starting the coding phase with declarations, built-ins, launching logic, then command execution.
Expanding POSIX Adherence
I'm now implementing the strtok functionality to split lines. I've also focused on the main loop, adding a prompt display using isatty(STDIN_FILENO) for interactive sessions. Specifically, I'm working to expand scripting support. I'll include shebangs and comments, although strtok adds some complexity to handle comments. The code review identified memory leaks as an issue that I'll need to address. Finally, my approach will provide the code and necessary compilation and usage instructions, while also clearly outlining why it's POSIX-like and what functionalities it omits.
Narrowing Project Scope
I'm now revising my presentation to clarify the project's scope: this is a "Simpleshell," a functional minimal shell that utilizes POSIX APIs, rather than full compliance. The explanation will encompass fork, exec, and the implementation of built-in commands. I will also include demonstrations of scripting. I'm focusing on improving the clarity of the code and adding comments, correcting includes, and reviewing my use of execvp.
Creating a fully 100% POSIX-certified shell (like dash or bash) is a project requiring thousands of lines of code to handle complex grammar, signal handling, variable expansion, and piping.
However, I can provide you with a functional, foundational shell in C that implements the core POSIX lifecycle: Read, Parse, Fork, Exec, and Wait.
This shell supports:
- Interactive Mode: A REPL (Read-Eval-Print Loop).
- Scripting Mode: Executing commands from a file.
- Built-ins:
cd, exit, and help.
- System Commands: Can run
ls, grep, python, etc., using standard $PATH.
The Code (myshell.c)
#define _GNU_SOURCE
#include <sys/wait.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
/*
Function Declarations for built-in shell commands:
*/
int lsh_cd(char **args);
int lsh_help(char **args);
int lsh_exit(char **args);
/*
List of builtin commands, followed by their corresponding functions.
*/
char *builtin_str[] = {
"cd",
"help",
"exit"
};
int (*builtin_func[]) (char **) = {
&lsh_cd,
&lsh_help,
&lsh_exit
};
int lsh_num_builtins() {
return sizeof(builtin_str) / sizeof(char *);
}
/*
Builtin function implementations.
*/
int lsh_cd(char **args)
{
if (args[1] == NULL) {
fprintf(stderr, "myshell: expected argument to \"cd\"\n");
} else {
if (chdir(args[1]) != 0) {
perror("myshell");
}
}
return 1;
}
int lsh_help(char **args)
{
printf("Simple POSIX-like Shell\n");
printf("Type program names and arguments, and hit enter.\n");
printf("The following are built in:\n");
for (int i = 0; i < lsh_num_builtins(); i++) {
printf(" %s\n", builtin_str[i]);
}
return 1;
}
int lsh_exit(char **args)
{
return 0;
}
/**
@brief Launch a program and wait for it to terminate.
@param args Null terminated list of arguments (including program).
@return Always returns 1, to continue execution.
*/
int lsh_launch(char **args)
{
pid_t pid, wpid;
int status;
pid = fork();
if (pid == 0) {
// Child process
if (execvp(args[0], args) == -1) {
perror("myshell");
}
exit(EXIT_FAILURE);
} else if (pid < 0) {
// Error forking
perror("myshell");
} else {
// Parent process
do {
wpid = waitpid(pid, &status, WUNTRACED);
} while (!WIFEXITED(status) && !WIFSIGNALED(status));
}
return 1;
}
/**
@brief Execute shell built-in or launch program.
@param args Null terminated list of arguments.
@return 1 if the shell should continue running, 0 if it should terminate
*/
int lsh_execute(char **args)
{
if (args[0] == NULL) {
// An empty command was entered.
return 1;
}
// Check for comments (basic support)
if (strncmp(args[0], "#", 1) == 0) {
return 1;
}
for (int i = 0; i < lsh_num_builtins(); i++) {
if (strcmp(args[0], builtin_str[i]) == 0) {
return (*builtin_func[i])(args);
}
}
return lsh_launch(args);
}
#define LSH_RL_BUFSIZE 1024
/**
@brief Read a line of input from stream.
@param stream The input stream (stdin or file).
@return The line from the stream.
*/
char *lsh_read_line(FILE *stream)
{
char *line = NULL;
size_t bufsize = 0; // have getline allocate a buffer for us
if (getline(&line, &bufsize, stream) == -1){
if (feof(stream)) {
free(line);
return NULL;
} else {
perror("readline");
exit(EXIT_FAILURE);
}
}
return line;
}
#define LSH_TOK_BUFSIZE 64
#define LSH_TOK_DELIM " \t\r\n\a"
/**
@brief Split a line into tokens (very basic parser).
@param line The line.
@return Null-terminated array of tokens.
*/
char **lsh_split_line(char *line)
{
int bufsize = LSH_TOK_BUFSIZE, position = 0;
char **tokens = malloc(bufsize * sizeof(char*));
char *token;
if (!tokens) {
fprintf(stderr, "myshell: allocation error\n");
exit(EXIT_FAILURE);
}
token = strtok(line, LSH_TOK_DELIM);
while (token != NULL) {
// Handle comments in middle of line
if (strncmp(token, "#", 1) == 0) {
break;
}
tokens[position] = token;
position++;
if (position >= bufsize) {
bufsize += LSH_TOK_BUFSIZE;
tokens = realloc(tokens, bufsize * sizeof(char*));
if (!tokens) {
fprintf(stderr, "myshell: allocation error\n");
exit(EXIT_FAILURE);
}
}
token = strtok(NULL, LSH_TOK_DELIM);
}
tokens[position] = NULL;
return tokens;
}
/**
@brief Loop getting input and executing it.
*/
void lsh_loop(FILE *input_stream)
{
char *line;
char **args;
int status;
int interactive = isatty(fileno(input_stream));
do {
if (interactive) {
printf("myshell> ");
}
line = lsh_read_line(input_stream);
// EOF reached
if (line == NULL) {
break;
}
args = lsh_split_line(line);
status = lsh_execute(args);
free(line);
free(args);
} while (status);
}
/**
@brief Main entry point.
@param argc Argument count.
@param argv Argument vector.
@return status code
*/
int main(int argc, char **argv)
{
FILE *input = stdin;
// Scripting Mode: If an argument is provided, assume it's a filename
if (argc > 1) {
input = fopen(argv[1], "r");
if (input == NULL) {
perror("myshell");
return EXIT_FAILURE;
}
}
// Run the loop
lsh_loop(input);
// Cleanup
if (input != stdin) {
fclose(input);
}
return EXIT_SUCCESS;
}
How to Compile and Run
- Save the code above as
myshell.c.
- Compile using GCC:
gcc -o myshell myshell.c
Feature 1: Interactive Mode
Run the shell without arguments to enter the Read-Eval-Print Loop.
./myshell
Output:
myshell> ls
myshell.c myshell
myshell> cd ..
myshell> pwd
/home/user
myshell> exit
Feature 2: Scripting Mode
You can create a text file containing commands, and this shell will execute them line-by-line. This demonstrates the scripting capability.
- Create a file named
test_script.sh:
# This is a comment
echo "Hello from script mode!"
ls -l
echo "Done listing files."
- Run your shell with the script as an argument:
./myshell test_script.sh
Alternatively, you can use the shebang method if you put myshell in your system path (like /usr/local/bin):
#!/usr/local/bin/myshell
echo "I am running inside myshell!"
Implementation Details (POSIX Concepts)
- Parser (
strtok): It tokenizes the input string based on white space. This is the most basic form of parsing. Real shells use Lex/Yacc or recursive descent parsers to handle quotes " ", pipes |, and redirections < >.
- Fork (
fork()): This syscall duplicates the current process. The shell (parent) makes a copy of itself (child).
- Exec (
execvp()): The child process replaces its memory image with the new program (e.g., ls). execvp is helpful because it automatically searches the PATH environment variable for the executable.
- Wait (
waitpid()): The parent shell pauses execution until the child process finishes. This prevents the shell prompt from reappearing before the command is done outputting.
- Built-ins: Commands like
cd must be built into the shell. If cd were an external binary, it would change the directory of the child process, then exit, leaving the parent shell in the old directory.
What is missing?
To be fully POSIX compliant (like /bin/sh), you would need to add:
- Pipes (
|): Creating pipes between processes.
- Redirection (
>, <): Manipulating file descriptors.
- Signals: Handling
Ctrl+C (SIGINT) correctly so it kills the current command, not the shell itself.
- Environment Variables: Logic to
export variables.
- Quotes: Handling arguments with spaces like
echo "hello world". Currently, this shell splits that into "hello and world".