I've been drilling down on the scope, particularly the POSIX compliance aspects. It's a vast undertaking! Right now, I'm focusing on parsing the specification to identify the core features and commands that are absolutely essential for a minimal, but functional, POSIX-compliant shell. This involves prioritizing and making some initial choices about the level of compliance to aim for in this initial iteration.
Assessing the MVP Features
I'm now carefully evaluating the features for the MVP. I've narrowed it down to the essential, non-negotiable functionalities, which seem to be the REPL, command parsing, execution, built-in commands (like cd and exit), script execution, and rudimentary variable handling. The challenge is balancing the scope with the time constraints. I am thinking the script support and variables can be made simpler to begin with.
Outlining the Implementation Strategy
I'm now sketching out the code architecture in my mind, considering how the pieces fit together. The core loop, parsing, execution flow, and built-in handling are becoming clearer, especially how to integrate the variable assignment and expansion. I'm focusing on the data structures required, particularly a linked list for variable storage. The fork and execvp calls are central to the process execution flow, so I'm finalizing their implementation details.
Formulating Implementation Details
The core structure is solidified: a main loop, input reading with getline, tokenization via strtok, and execution using fork and execvp. I've shifted from custom variable storage to leveraging setenv and getenv for simplicity. Next, I am finalizing how to best handle the built-in commands and how I can best test the overall implementation.
Evaluating the Code Structure
I'm now consolidating the code structure. I've successfully implemented the REPL, and the core parsing, execution, and built-in functions are working. My focus has shifted toward variable expansion using getenv and setenv, alongside adding conditional logic using a state machine. I am currently integrating error handling and preparing the code for testing.
Reviewing the Tokenizer
I'm now deep-diving into the code. The strtok is proving adequate for now, especially with the limited scope, but I'm considering potential issues with reentrancy down the line. I'm focusing on error checking for execvp and also on creating a state machine for the if implementation, which I believe is achievable with the chosen implementation.
Writing a fully 100% POSIX-compliant shell (like dash or bash) requires thousands of lines of code to handle complex grammar, signals, piping syntax (|), and redirections (>, <).
However, I can provide you with a functional, minimal C implementation that adheres to the core POSIX API standards (fork, exec, wait, environ) and includes scripting capabilities (variables, comments, and file execution).
We will call this nanosh.
Features of nanosh
REPL: Interactive command line interface.
Scripting: Can execute .nsh files.
Built-ins:cd, exit, export.
Environment: Inherits and modifies environment variables.
Variable Expansion: Supports $VAR syntax.
Process Management: Proper fork/execvp implementation.
The Code (nanosh.c)
Save the following code into a file named nanosh.c.
c
How to Compile and Run
Compile:
Use GCC or any standard C compiler.
bash
gcc -o nanosh nanosh.c
Run Interactively:
bash
./nanosh
Run a Script:
Create a file named test.nsh:
bash
# This is a nanosh script
export USER=Guest
echo Hello $USER
cd /tmp
pwd
Run it:
bash
./nanosh test.nsh
Scripting Capabilities Explanation
This shell implements the Fork-Exec model, which is the heart of POSIX process management.
Variables (export & $):
I implemented lsh_export which uses the standard setenv C function.
Before executing a command, the function expand_variables scans arguments for the $ symbol and uses getenv to replace them.
Example usage:export NAME=John, then echo $NAME.
File Execution (Scripting):
The main function checks argc. If an argument is provided, it opens that file via fopen.
It passes the file pointer to lsh_loop.
The loop reads from the file pointer exactly as it would stdin. This is how Unix treats streams uniformly.
Comments:
The tokenizer checks for #. If found, it stops parsing the current line, effectively ignoring the rest of the text.
Built-ins:
cd: Standard commands like cd cannot be external programs because a child process cannot change the parent's working directory. We implement this using chdir().
Limitations (Why this isn't Bash yet)
Pipes:ls | grep txt is not implemented (requires pipe() and dup2()).
Logic: No if, else, or while loops (requires a syntax tree parser).
Quotes: Doesn't handle "multi word strings" (tokenizer splits strictly on spaces).
This implementation provides the "skeleton" of a shell, strictly following POSIX system calls to interact with the kernel.
#define _POSIX_C_SOURCE 200809L
#include <sys/wait.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
/* Configuration constants */
#define LSH_TOK_BUFSIZE 64
#define LSH_TOK_DELIM " \t\r\n\a"
/* Function Declarations for built-in shell commands */
int lsh_cd(char **args);
int lsh_help(char **args);
int lsh_exit(char **args);
int lsh_export(char **args);
/* List of builtin commands, followed by their corresponding functions. */
char *builtin_str[] = {
"cd",
"help",
"exit",
"export"
};
int (*builtin_func[]) (char **) = {
&lsh_cd,
&lsh_help,
&lsh_exit,
&lsh_export
};
int lsh_num_builtins() {
return sizeof(builtin_str) / sizeof(char *);
}
/* Built-in function implementations */
// IMPLEMENTATION OF cd
int lsh_cd(char **args) {
if (args[1] == NULL) {
fprintf(stderr, "lsh: expected argument to \"cd\"\n");
} else {
if (chdir(args[1]) != 0) {
perror("lsh");
}
}
return 1;
}
// IMPLEMENTATION OF help
int lsh_help(char **args) {
printf("NanoSH - A Minimal POSIX Shell\n");
printf("Type program names and arguments, or hit enter.\n");
printf("Built-in commands:\n");
for (int i = 0; i < lsh_num_builtins(); i++) {
printf(" %s\n", builtin_str[i]);
}
printf("Use the man command for information on other programs.\n");
return 1;
}
// IMPLEMENTATION OF exit
int lsh_exit(char **args) {
return 0;
}
// IMPLEMENTATION OF export (KEY=VALUE)
int lsh_export(char **args) {
if (args[1] == NULL) {
fprintf(stderr, "lsh: expected argument for export (KEY=VALUE)\n");
return 1;
}
char *key = strtok(args[1], "=");
char *val = strtok(NULL, "=");
if (key && val) {
setenv(key, val, 1);
} else {
fprintf(stderr, "lsh: invalid format. Use KEY=VALUE\n");
}
return 1;
}
/* Process Launching */
int lsh_launch(char **args) {
pid_t pid;
int status;
pid = fork();
if (pid == 0) {
// Child process
if (execvp(args[0], args) == -1) {
perror("lsh");
}
exit(EXIT_FAILURE);
} else if (pid < 0) {
// Error forking
perror("lsh");
} else {
// Parent process
do {
waitpid(pid, &status, WUNTRACED);
} while (!WIFEXITED(status) && !WIFSIGNALED(status));
}
return 1;
}
/* Variable Expansion (simple $VAR handling) */
void expand_variables(char **args) {
for (int i = 0; args[i] != NULL; i++) {
if (args[i][0] == '$') {
char *env_val = getenv(args[i] + 1); // Skip '$'
if (env_val != NULL) {
args[i] = env_val;
}
}
}
}
/* Execute Shell Command */
int lsh_execute(char **args) {
if (args[0] == NULL) {
// An empty command was entered.
return 1;
}
// Handle comments
if (strncmp(args[0], "#", 1) == 0) {
return 1;
}
// Expand variables handled here
expand_variables(args);
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);
}
/* Line Splitter (Tokenizer) */
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, "lsh: allocation error\n");
exit(EXIT_FAILURE);
}
token = strtok(line, LSH_TOK_DELIM);
while (token != NULL) {
// Handle inline comments
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, "lsh: allocation error\n");
exit(EXIT_FAILURE);
}
}
token = strtok(NULL, LSH_TOK_DELIM);
}
tokens[position] = NULL;
return tokens;
}
/* Line Reader */
char *lsh_read_line(FILE *input) {
char *line = NULL;
size_t bufsize = 0; // getline will allocate a buffer for us
if (getline(&line, &bufsize, input) == -1) {
if (feof(input)) {
free(line);
exit(EXIT_SUCCESS);
} else {
perror("readline");
exit(EXIT_FAILURE);
}
}
return line;
}
/* Main Loop */
void lsh_loop(FILE *input) {
char *line;
char **args;
int status;
do {
// Only print prompt if interactive
if (input == stdin && isatty(STDIN_FILENO)) {
printf("> ");
}
line = lsh_read_line(input);
args = lsh_split_line(line);
status = lsh_execute(args);
free(line);
free(args);
} while (status);
}
/* Entry Point */
int main(int argc, char **argv) {
// 1. Load config files (omitted)
// 2. Run Loop
if (argc == 1) {
// Interactive Mode
lsh_loop(stdin);
} else {
// Script Mode
FILE *f = fopen(argv[1], "r");
if (!f) {
perror("lsh");
return EXIT_FAILURE;
}
lsh_loop(f);
fclose(f);
}
// 3. Shutdown/Cleanup
return EXIT_SUCCESS;
}