-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuffer.c
More file actions
executable file
·115 lines (101 loc) · 2.67 KB
/
Copy pathbuffer.c
File metadata and controls
executable file
·115 lines (101 loc) · 2.67 KB
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
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <signal.h>
#include "buffer.h"
// our vec doubles in size each realloc, this is the constant representing that
const int capacityMul = 2;
void push(Processes* buffer, Child elem)
{
int cap = buffer->cap;
cap = cap == 0 ? 1 : cap;
int len = buffer->len;
if (buffer->cap == len) {
int newSize = cap * capacityMul;
buffer->buf = realloc(buffer->buf, newSize * sizeof(Child));
buffer->cap = newSize;
}
buffer->buf[len] = elem;
buffer->len += 1;
}
Processes new_buffer()
{
Child* buf = (Child*)calloc(0, sizeof(Child));
Processes s = {.len = 0, .cap = 0, buf};
return s;
}
void remove_child(Processes* buffer, int i)
{
Child* child = &buffer->buf[i];
child->cmd = NULL;
close(child->input[writer]);
close(child->output[reader]);
close(child->error[reader]);
/*for(int j = i; j < buffer->len - 1; j++) {
buffer->buf[i] = buffer->buf[i+1];
}
buffer->len -= 1;*/
}
void kill_all(Processes* buffer) {
for(int i = 0; i < buffer->len; i++) {
Child child = buffer->buf[i[;
kill(child.pid, SIGTERM);
}
sigset_t set;
sigemptyset(&set);
sigaddset(&set, SIGCHILD);
sigprocmask(SIG_BLOCK, &set, NULL);
siginfo_t info;
int ndead = 0;
int dead[] = calloc(buffer->len, sizeof(int));
struct timespec time = { .tv_sec = 1, 0 };
while(1) {
int wait = sigtimedwait(&set, &info, &time);
int finished = wait == -1 && errno == EAGAIN;
if(finished) break;
int pid = info.si_pid;
dead[ndead] = pid;
ndead++;
}
for(int j = 0; j < ndead; j++) {
waitpid(dead[j], NULL, 0);
}
for(int i = 0; i < buffer->len; i++) {
int killed = 0;
Child child = buffer->buf[i];
for(int j = 0; j < ndead; j++) {
if(child.pid == dead[j]) {
killed = 1;
break;
}
}
if(!killed) {
kill(pid, SIGKILL);
}
}
clear(buffer);
}
void tighten(Processes* buffer) {
int i;
for(i = 0; i < buffer->len;) {
Child child = buffer->buf[i];
if(child.cmd == NULL) {
for(int j = i; j < buffer->len - 1; j++) {
buffer->buf[i] = buffer->buf[i+1];
}
buffer->len -= 1;
} else {
//since when the inner for loop runs
//buffer[i] may still be null we shouldnt increment
//we shoudl check buffer[i] again
i++;
}
}
}
void clear(Processes* buffer)
{
buffer->len = 0;
}