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
90
91
92
93
94
95
96
97
98
99
100
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/param.h>
#include <errno.h>
#include "main.h"
#include "helper_functions.c"
#include "lsh_main_func.c"
#include "lsh_split_line.c"
#include "lsh_builtins.c"
void lsh_loop(SHELL_OB *shell_obj){
char *line;
char **args;
CMD **cmds;
int status;
do {
//get pwd
char *cwd= getenv("PWD");
char *pwd=basename(cwd);
if(pwd==NULL){
fprintf(stderr,"lsh:pwd is null\n\n");
exit(EXIT_FAILURE);
}
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();
cmds = lsh_split_command(line);
int j=0;
while (cmds[j]){
args = lsh_split_line(cmds[j]->cmd);
status = lsh_execute(args,cmds[j]);
j++;
int i=0;
while (args[i])
free(args[i++]);
free(args);
}
int i=0;
while(cmds[i]){
if(cmds[i]->out_dir!=NULL) free(cmds[i]->out_dir);
free(cmds[i]);
i++;
}
free(cmds);
free(line);
} while (status);
}
static char* call_realpath (char * argv0) {
char* resolved_path=(char*)malloce(sizeof(char)*PATH_MAX);
if (realpath (argv0, resolved_path) == 0) {
fprintf (stderr, "lsh: realpath failed: %s\n", strerror (errno));
exit(errno);
}
else {
return resolved_path;
}
}
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);
}
char* prog_path = call_realpath(argv[0]);
setenv("SHELL",prog_path,1);
//Set The prompt
SHELL_OB shell_obj;
shell_obj.prompt = (char *)malloce(sizeof(char) * 1024);
shell_obj.pre_prompt = (char *)malloce(sizeof(char) * 1024);
//get the hostname
char *hostname = (char *)malloce(sizeof(char) * 1024);
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);
free(prog_path);
return EXIT_SUCCESS;
}
|