-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.c
109 lines (82 loc) · 2.67 KB
/
main.c
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
101
102
103
104
105
106
107
108
109
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<fcntl.h>
#include<sys/types.h>
#include<sys/wait.h>
#define LINE_LEN 80
#define MAX_ARGS 64
#define MAX_ARG_LEN 16
#define MAX_PATHS 9
#define MAX_PATH_LEN 96
#define WHITESPACE " .,\t\n"
#ifndef NULL
#define NULL ...
#endif
#include"minishell.h"
int main()
{
struct command_t command; // stores command, argv and argc
char *dir[20]; // stores directories
const char*CLEAR_SCREEN_ANSI = "\e[1;1H\e[2J";
write(STDOUT_FILENO, CLEAR_SCREEN_ANSI, 10); // clear screen
while(1)
{
for(int i=0;i<20;i++)
{
dir[i] = malloc(30); // allocating dynamic memory
}
print_prompt(); // print prompt
command.argc = read_command(command.name, command.argv); // reading command
if(strcmp(command.name, "exit")==0) // if command is exit
{
break;
}
command.argv[command.argc]= NULL; // making null terminated
parsePath(dir); // parsing path
char* path = lookupPath(command.argv,dir); // getting exact path
if(path!=NULL)
{
int pid= fork(); // making child process
if(pid==0)
{
execv(path, command.argv); // running execv in child process
printf("\nError\n"); // print error in case of failure
}
else
{
wait(NULL);
for(int i=0;i<20;i++)
{
free(dir[i]); // free the dynamic memory
}
for(int i=0;i<command.argc;i++)
{
free(command.argv[i]); // free dynamic memory of argv which is in command struct
}
}
}
else
{
sleep(1);
for(int i=0;i<20;i++)
{
free(dir[i]); // free the dynamic memory
}
for(int i=0;i<command.argc;i++)
{
free(command.argv[i]); // free dynamic memory of argv which is in command struct
}
}
}
for(int i=0;i<20;i++)
{
free(dir[i]); // free the dynamic memory
}
for(int i=0;i<command.argc;i++)
{
free(command.argv[i]); // free dynamic memory of argv which is in command struct
}
return 0;
}