-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.c
140 lines (124 loc) · 3.11 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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
#include "Headers.h"
#include "Username.h"
#include "pwd.h"
#include "cd.h"
#include "ls.h"
#include "echo.h"
#include "parse.h"
#include "curdir.h"
#include "pinfo.h"
#include "history.h"
#define start_dir getenv("PWD")
int background_count=0;
background_jobs background[20];
int fg_process_id = -1;
char fg_process_name[100];
void Handler(int p)
{
fflush(stdout);
for(int i=0; i<20; i++)
{
int status;
pid_t return_pid = waitpid(background[i].id, &status, WNOHANG);
if(return_pid == background[i].id && return_pid == background[i].id!=0)
{
printf("%s Process with pid %d exited ",background[i].name , background[i].id);
background[i].id = 0;
background[i].name[0]='\0';
background_count--;
if(status == 0)
{
printf("Normally\n");
fflush(stdout);
Username();
curdir(start_dir);
}
else
{
printf("Abnormally\n");
Username();
curdir(start_dir);
fflush(stdout);
}
}
}
}
void Push_to_background(int p)
{
if(fg_process_id!=-1)
{
kill(fg_process_id, SIGTSTP);
//strcpy(background[background_count].name, "Foreground Process");
strcpy(background[background_count].name,fg_process_name);
background[background_count].number = background_count;
background[background_count].id = fg_process_id;
background_count++;
}
printf("\n");
Username();
curdir(start_dir);
fflush(stdout);
}
void KillForegroundProcess(int p)
{
//kill(getpid(),SIGINT);
if(fg_process_id!=-1)
{
kill(fg_process_id,SIGINT);
fg_process_id=-1;
}
printf("\n");
Username();
curdir(start_dir);
fflush(stdout);
}
void exit_handler(int p)
{
exit(1);
}
int main()
{
for(int i=0; i<20; i++)
{
background[i].id = 0;
}
char pwd[1000];
strcpy(pwd,start_dir);
char str[100][256];
int status = 1;
char *in_line;
ssize_t len = 0;
ssize_t buffer_size=1000;
signal(SIGCHLD, Handler);
signal(SIGINT, KillForegroundProcess);
//signal(SIGTSTP, KillForegroundProcess);
signal(SIGTSTP, Push_to_background);
while(1)
{
fflush(stdout);
len=0;
Username();
curdir(pwd);
//signal(SIGCHLD, Handler);
//signal(SIGINT, Continue);
len = getline(&in_line,&buffer_size,stdin);
if(Check_History(pwd,in_line))
{
Write_History(pwd,in_line);
}
if(len==-1)
{
printf("\033[0:31m");
printf("THANK YOU\n");
exit(1);
}
if(in_line[len-1]=='\n')
{
in_line[len-1]='\0';
}
strcpy(fg_process_name, in_line);
check_commands(in_line,background,&background_count,pwd, &fg_process_id);
in_line[len-1]='\n';
fflush(stdout);
}
}