Skip to content

Instantly share code, notes, and snippets.

@ggreenleaf
Created October 3, 2014 15:44
/*
* sh1.c: sample version 1 of a UNIX command shell/interpreter.
* Stefan Brandle, COS 421, Feb 2000. Mod Feb 2001.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
//prototypes
//parse a command into array of arguments
//arg[0] command
//arg[1--(n-1)] arguments
//arg[n] NULL
void parsecmd(char*, char**); //parse command into array of arguments
void exec(char**); //run command
int main()
{
char line[256];
char prompt[] = "grsh$";
char * argv[64]; //cmd line arguments
/* spit out the prompt */
printf("%s", prompt );
/* Try getting input. If error or EOF, exit */
while( fgets(line, sizeof line, stdin) != NULL )
{
/* fgets leaves '\n' in input buffer. ditch it */
line[strlen(line)-1] = '\0';
/* This is where I take the easy route.
system(line);
fork(), execvp() & co. go here in your version*/
//printf("%s", prompt);
parsecmd(line, argv);
if (strcmp(*argv,"list") == 0)
*argv = "ls"; //change first argument to ls command
else if (strcmp(*argv,"exit") == 0 )
exit(0);
exec(argv);
printf("%s",prompt);
}
return 0;
}
//taken from csl.mtu.edu
void parsecmd(char *line, char **argv)
{
while (*line != '\0') /* if not the end of line ....... */
{
while (*line == ' ' || *line == '\t' || *line == '\n')
*line++ = '\0'; /* replace white spaces with 0 */
*argv++ = line; /* save the argument position */
while (*line != '\0' && *line != ' ' &&
*line != '\t' && *line != '\n')
line++; /* skip the argument until ... */
}
*argv = '\0'; /* mark the end of argument list */
}
void exec(char** argv)
{
int pid = fork();
if (pid == 0 ) //child process
{
execvp(*argv, argv);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment