-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjobs.c
124 lines (115 loc) · 3.3 KB
/
jobs.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
#include "headers.h"
#include "jobs.h"
#include "process_list.h"
extern p_list* head;
extern time_t time_;
int cmp_jobs(const void* a, const void* b)
{
char* x = (*((p_list**) a))->command;
char* y = (*((p_list**) b))->command;
return strcasecmp(x, y);
}
void A_Shell_jobs(int flags)
{
// flag = 1 -> no flag, 2 -> -r, 3 -> -s, 6 -> -rs
p_list* list[MAX_JOBS];
int num_jobs = 0;
for(p_list* i = head->next; i != NULL; i= i->next)
{
if(i->pid != -1)
{
list[num_jobs++] = i;
}
}
qsort(list, num_jobs, sizeof(p_list*), cmp_jobs);
for(int i = 0; i < num_jobs; i++)
{
if(list[i]->status == 'T' && flags != 2)
printf("[%d] Stopped %s [%d]\n", list[i]->index, list[i]->command, list[i]->pid);
if(list[i]->status == 'R' && flags != 3)
printf("[%d] Running %s [%d]\n", list[i]->index, list[i]->command, list[i]->pid);
// printf("[%d] %c %s [%d]\n", list[i]->index, state, list[i]->command, list[i]->pid);
}
}
void A_Shell_sig(int job_index, int signal_)
{
for(p_list* i = head->next; i != NULL; i=i->next)
{
if(i->index == job_index)
{
if(i->pid == -1)
{
fprintf(stderr, C_ERROR"A-Shell: sig: no job with index [%d] exists\n", job_index);
fflush(NULL);
return;
}
kill(i->pid, signal_);
if(signal_ == 19)
{
i->status = 'T';
}
return;
}
}
fprintf(stderr, C_ERROR"A-Shell: sig: no job with index [%d] exists\n", job_index);
fflush(NULL);
}
void A_Shell_fg(int job_index)
{
for(p_list* i = head->next; i != NULL; i=i->next)
{
if(i->index == job_index)
{
if(i->pid == -1)
{
fprintf(stderr, C_ERROR"A-Shell: fg: no job with index [%d] exists\n", job_index);
fflush(NULL);
return;
}
tcsetpgrp(STDIN_FILENO, i->pid);
if(i->status == 'T')
{
kill(i->pid, SIGCONT);
}
int w;
time_t t1 = time(NULL);
waitpid(i->pid, &w, WUNTRACED);
time_t t2 = time(NULL);
time_ = t2 - t1;
if(!WIFSTOPPED(w))
{
i->pid = -1;
free(i->command);
i->command = NULL;
i->status = 'Z';
}
tcsetpgrp(STDOUT_FILENO, getpid());
return;
}
}
fprintf(stderr, C_ERROR"A-Shell: fg: no job with index [%d] exists\n", job_index);
fflush(NULL);
}
void A_Shell_bg(int job_index)
{
for(p_list* i = head->next; i != NULL; i=i->next)
{
if(i->index == job_index)
{
if(i->pid == -1)
{
fprintf(stderr, C_ERROR"A-Shell: bg: no job with index [%d] exists\n", job_index);
fflush(NULL);
return;
}
if(i->status == 'T')
{
i->status = 'R';
kill(i->pid, SIGCONT);
}
return;
}
}
fprintf(stderr, C_ERROR"A-Shell: bg: no job with index [%d] exists\n", job_index);
fflush(NULL);
}