CookiJar
2013-01-24 08:59:52 UTC
#include
#include
#include
#include
#include
#define MAX_ARGS 64
#define LINE_LEN 80
#define MAX_ARG_LEN 16
#define MAX_PATHS 64
#define MAX_PATH_LEN 96
#define WHITESPACE " .,\n\t"
#ifndef NULL
#define NULL
#endif
struct command_t {
char *name;
int argc;
char *argv[MAX_ARGS];
};
char *lookupPath(char **, char **);
int parseCommand(char *, struct command_t *);
int parsePath(char **);
void printPrompt();
void readCommand(char *);
int parsePath(char* dirs[]) {
int i;
int j = 1;
char *parsePathEnv;
char *thePath;
for(i=0; i
parsePathEnv = (char *) getenv("PATH");
thePath = (char*) malloc(strlen(parsePathEnv) + 1);
strcpy(thePath, parsePathEnv);
dirs[j] = strtok(thePath, ":");
//j = 1;
while(1)
{
dirs[j] = strtok(NULL, ":");
if(dirs[j] == NULL)
break;
j++;
}
}
char *lookupPath(char **argv, char **dirs) {
char *result;
char pName[MAX_PATH_LEN];
int i;
if(*argv[0] == '/')
{
if(access(argv[0], X_OK) == 0)
{
result = (char *) malloc(strlen(argv[0]) + 1);
strcpy(result, argv[0]);
}
else
{
printf("\nError!");
result = NULL;
}
}
else
{
for(i=0; i
strcpy(pName, dirs[i]);
strcat(pName, "/");
strcat(pName, argv[0]);
if(access(pName, X_OK) == 0)
{
result = (char *) malloc(strlen(pName) + 1);
strcpy(result, pName);
}
else
{
printf("\nError!");
result = NULL;
}
}
}
return result;
}
void printPrompt() {
char promptString[] = "osProj1# ";
printf("%s", promptString);
}
void readCommand(char *buffer) {
gets(buffer);
}
int parseCommand(char *cLine, struct command_t *cmd) {
int argc;
char **clPtr;
argc = 0;
cmd->argv[argc] = (char *) malloc(MAX_ARG_LEN);
while((cmd->argv[argc] = strsep(clPtr, WHITESPACE)) != NULL) {
cmd->argv[++argc] = (char *) malloc(MAX_ARG_LEN);
}
cmd->argc = argc - 1;
cmd->name = (char *) malloc(sizeof(cmd->argv[0]));
strcpy(cmd->name, cmd->argv[0]);
return 1;
}
int main() {
int status, pid;
char *parsePathEnv;
char *pathv[MAX_PATH_LEN];
char commandLine[LINE_LEN];
struct command_t command;
parsePathEnv = (char *) getenv("PATH");
printf("%s", parsePathEnv);
parsePath(pathv);
while(1) {
printPrompt();
readCommand(commandLine);
parseCommand(commandLine, &command);
command.argv[command.argc] = NULL;
command.name = lookupPath(command.argv, pathv);
if(command.name == NULL) {
printf("\nInvalid command");
continue;
}
if((pid = fork()) == 0) {
execv(command.name, command.argv);
}
wait(&status);
}
return 0;
}