aboutsummaryrefslogtreecommitdiff
path: root/src/main.c
blob: 15830acda9d75d9146364c8334f522bba171f4a4 (plain)
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
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#include "helper_functions.c"
#include "lsh_main_func.c"
#include "lsh_builtins.c"

typedef struct{
    char *prompt;
    char *pre_prompt;
} SHELL_OB;

void lsh_loop(SHELL_OB *shell_obj)
{
    char *line;
    char **args;
    int status;

    do {
        //get pwd
        char *cwd= getenv("PWD");
        char *pwd=basename(cwd);
        snprintf(shell_obj->prompt,sizeof(char) * 1024,"%s %s> ",shell_obj->pre_prompt,pwd);
        free(pwd);
        printf("%s",shell_obj->prompt);
        line = lsh_read_line();
        args = lsh_split_line(line);
        status = lsh_execute(args);

        free(line);
        free(args);
    } while (status);
}

int main(int argc, char **argv){
    //set sh level
    char *shlvl = getenv("SHLVL");
    if(shlvl != NULL){
        int shlvli = atoi(shlvl);
        shlvli++;
        sprintf(shlvl,"%d",shlvli);
        setenv("SHLVL",shlvl,1);
    }

    //Set The prompt
    SHELL_OB shell_obj;
    shell_obj.prompt = (char *)malloc(sizeof(char) * 1024);
    if (!shell_obj.prompt){
        fprintf(stderr, "lsh: allocation error\n");
        exit(EXIT_FAILURE);
    }
    shell_obj.pre_prompt = (char *)malloc(sizeof(char) * 1024);
    if (!shell_obj.pre_prompt){
        fprintf(stderr, "lsh: allocation error\n");
        exit(EXIT_FAILURE);
    }

    //get the hostname
    char *hostname = (char *)malloc(sizeof(char) * 1024);
    if (!hostname) {
        fprintf(stderr, "lsh: allocation error\n");
        exit(EXIT_FAILURE);
    }
    gethostname(hostname,sizeof(char) * 1024);

    //set the pre_prompt
    snprintf(shell_obj.pre_prompt,sizeof(char) * 1024,"%s@%s",getenv("USER"),hostname);
    free(hostname);

    lsh_loop(&shell_obj);

    free(shell_obj.prompt);
    free(shell_obj.pre_prompt);
    return EXIT_SUCCESS;
}