post

poster: jsaxton
description: Very, very basic shell
language: C
[download]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#include<stdio.h>
#include<malloc.h>
#include<string.h>
#include<sys/types.h>
#include<sys/wait.h>

#define INIT_SIZE 20

void getInput(char** string);

int main() {
    char* command;    //points to the command
    char* argv[500];
    int index=0;
    char* element;
    pid_t mypid;
    int i;
    
    while(1) {
        printf("mysh > ");
        getInput(&command);
        if(strcmp(command, "exit") == 0) {
            return 1;
        }
        
        //let's handle the command
        element = strtok(command, " ");
        while(element != NULL) {
            argv[index] = (char *)malloc(sizeof(char)*strlen(element));
            strcpy(argv[index], element);
            element = strtok(NULL, " ");
            index++;
        }
        
        argv[index] = NULL;
        mypid=fork();
        wait(NULL);
        if(mypid==0) {
            execvp(argv[0], argv);
        }
        else {
            for(i=index;i>=0;i--) {
                free(argv[i]);
            }
            index=0;
        }
    }
    
    return 0;
}


//This function retrieves a line from STDIN.
//The line can be of arbitrary length
void getInput(char **inputstr) {
    char c;
    int arrsize=INIT_SIZE;
    int charindex=0;
    int i;
    *inputstr = (char*)malloc(sizeof(char)*arrsize);
    while((c = getchar()) != '\n') {
        //Check to see if we need to expand the array
        if(charindex == (arrsize-2)) {
            //increase the size of the array
            arrsize *= 2;

            //create a temp array
            char* temp = malloc(sizeof(char)*arrsize);

            //Copy the old array into the new temp array
            for(i=0; i<=charindex; i++) {
                temp[i] = (*inputstr)[i];
            }

            //we no longer need inputstr
            free(*inputstr);

            //reassignment
            *inputstr=temp;
        }
        
        //Do this regardless of whether or not the array needs expansion
        (*inputstr)[charindex] = c;
        charindex++;
    }
    
    //append a null terminator
    (*inputstr)[charindex] = '\0';
}