Skip to content

Commit 051f706

Browse files
committed
sched: free up thread and process memory after waitpid()
1 parent 5dd14a8 commit 051f706

File tree

2 files changed

+79
-1
lines changed

2 files changed

+79
-1
lines changed

src/sched/cleanup.c

+79
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
/*
2+
* lux - a lightweight unix-like operating system
3+
* Omar Elghoul, 2024
4+
*
5+
* Core Microkernel
6+
*/
7+
8+
#include <string.h>
9+
#include <stdlib.h>
10+
#include <kernel/sched.h>
11+
#include <platform/platform.h>
12+
13+
/* threadCleanup(): frees all memory associated with a thread and removes it
14+
* from the run queues
15+
* params: t - thread structure
16+
* returns: nothing
17+
*/
18+
19+
void threadCleanup(Thread *t) {
20+
platformCleanThread(t->context, t->highest);
21+
22+
Process *pc = getProcess(t->pid);
23+
Process *pq = getProcessQueue();
24+
Thread *tq;
25+
26+
while(pq) {
27+
if(!pq->threadCount || !pq->threads) {
28+
pq = pq->next;
29+
continue;
30+
}
31+
32+
for(int i = 0; i < pq->threadCount; i++) {
33+
if(pq->threads[i] == t) {
34+
if(i != pq->threadCount-1)
35+
memmove(&pq->threads[i], &pq->threads[i+1], (pq->threadCount-i) * sizeof(Thread *));
36+
else
37+
pq->threads[i] = NULL;
38+
39+
pq->threadCount--;
40+
break;
41+
} else {
42+
// remove from the next queues as well
43+
tq = pq->threads[i];
44+
if(tq->next == t) tq->next = t->next;
45+
}
46+
}
47+
48+
pq = pq->next;
49+
}
50+
51+
// now remove the process that contains this thread if necessary
52+
if(!pc->threadCount) {
53+
pq = getProcessQueue();
54+
55+
while(pq) {
56+
if(pq->next == pc) pq->next = pc->next;
57+
pq = pq->next;
58+
}
59+
60+
pq = getProcess(pc->parent);
61+
for(int i = 0; i < pq->childrenCount; i++) {
62+
if(pq->children[i] == pc) {
63+
if(i != pq->childrenCount-1)
64+
memmove(&pq->children[i], &pq->children[i+1], (pq->childrenCount-i) * sizeof(Process *));
65+
else
66+
pq->children[i] = NULL;
67+
68+
pq->childrenCount--;
69+
break;
70+
}
71+
}
72+
73+
free(pc->children);
74+
free(pc->threads);
75+
free(pc);
76+
}
77+
78+
free(t);
79+
}

src/sched/waitpid.c

-1
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,6 @@ static pid_t processStatus(Process *p, int *status) {
3131

3232
// free the thread structure
3333
threadCleanup(t);
34-
3534
return pid;
3635
}
3736
}

0 commit comments

Comments
 (0)