-
Notifications
You must be signed in to change notification settings - Fork 0
/
threads.c
105 lines (90 loc) · 2.16 KB
/
threads.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
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <signal.h>
#define THREADS 1000
void readFileAgain();
void createOrRemoveThreads();
void sigIntFunc();
void hupFunc();
int inputCount = 0;
int threadCount = 0;
pid_t ppid;
pthread_t p[THREADS];
void *no_work(void *);
int main(void)
{
ppid = getpid();
printf("I am parent with pid: %d\n", ppid);
signal(SIGHUP, hupFunc);
signal(SIGINT, sigIntFunc);
readFileAgain();
// join all threads before finishing
for(int i = 0; i < threadCount; i++){
pthread_join(p[i], NULL);
}
return EXIT_SUCCESS;
}
void *no_work(void *arg)
{
(void) arg;
printf("Thread %lu is starting\n", pthread_self());
while(1)
{
sleep(1);
}
return NULL;
}
void sigIntFunc()
{
for(int i = threadCount-1; i > -1; i--){
printf("%lu is being killed\n", p[i]);
fflush(stdout);
pthread_cancel(p[i]);
}
}
void hupFunc()
{
readFileAgain();
}
void createOrRemoveThreads()
{
// signal(SIGINT, sigIntFunc);
if(threadCount < inputCount){
//add threads
for(int i = threadCount; i < inputCount; i++){
pthread_create(&p[i], NULL, no_work, NULL);
threadCount++;
}
} else if (threadCount == inputCount){
printf("Same same");
} else {
//remove
for(int i = threadCount-1; i > inputCount-1; i--)
{
printf("%lu is going to a good place, RIP.\n", p[i]);
pthread_cancel(p[i]);
threadCount--;
}
}
}
void readFileAgain()
{
printf("Reading Config File...\n");
FILE *fd;
if((fd = fopen("config.txt", "r")) != NULL){
fscanf(fd, "%d", &inputCount);
fclose(fd);
} else {
perror("Program exited with following code");
exit(1);
}
printf("Changing settings to %d\n", inputCount);
if( inputCount < 1){
printf("The process count should be at least 1. Exiting\n");
exit(1);
} else {
createOrRemoveThreads();
}
}