Back to Code List
c

Simple Shell

This is a simple implementation to simulate a terminal shell prompt. It uses a child process to run the execvp command with any user input.

   main.c

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>

#define MAX_LINE 512
char **args;

int execute(char **args)
{
	pid_t pid;
	pid = fork();

	if (pid == 0)
	{
		execvp(*args,args);
		printf("  Unknown command\n");
		exit(EXIT_FAILURE);
	}
	else
	{
		wait(NULL);
		return 1;
	}
	return 0;
}

int parse(char *input, char**args)
{
    char * p = strtok(input," ");
    int s = 0;
    
    while (p) {
        args = realloc(args,sizeof(char*)*(++s));
        args[s-1] = p;
        p = strtok(NULL," ");
    }

    args = realloc(args,sizeof(char*)*(s+1));
    args[s] = NULL;
    
	//this loop sets our argc
	int i=0;
    for (; i < (s+1); ++i);

	return i-1;
}

int main(void)
{
	args = malloc(MAX_LINE);
	char input[MAX_LINE];

	while (1)
	{
		printf("osh>");
		fflush(stdout);
		
		// get user input full line
		fgets(input, MAX_LINE, stdin);
		
		if(strcmp(&input[0], "\n") == 0) continue;
		strtok(input, "\n");
		if(strcmp(&input[0], "exit") == 0) break;
		
		// parse input into *args
		int argc = parse(input,args);
		if (argc == 0) continue;
		
		execute(args);
	}
	return 0;
}