This repository was archived by the owner on Jul 25, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwriteOutput.c
More file actions
109 lines (85 loc) · 2.74 KB
/
Copy pathwriteOutput.c
File metadata and controls
109 lines (85 loc) · 2.74 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
// take list message and write to screen
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>
#include "list.h"
#include "queueOperations.h"
#include "writeOutput.h"
// Max size of the message, using theoretical max length for a UDP packet of 65507 - 1 byte for null terminator
#define MAXBUFLEN 65506
static pthread_t writerThread;
static pthread_mutex_t writeAvailableCondMutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t writeAvailableCond = PTHREAD_COND_INITIALIZER;
static List* list;
static char* message;
static void* writeLoop(void* useless){
while(1)
{
// Waits the write funtion, will be signalled by receiveUDP
pthread_mutex_lock(&writeAvailableCondMutex);
{
pthread_cond_wait(&writeAvailableCond, &writeAvailableCondMutex);
}
pthread_mutex_unlock(&writeAvailableCondMutex);
int iteration = 0;
do
{
iteration ++;
// Taking message from list
message = dequeueMessage(list);
if(message==NULL)
{
fprintf(stderr, "writer: dequeue error, queue empty.\n");
break;
}
int writeVar = write(1,message, strlen(message)); // will put the message from first list onto screen
if(writeVar == -1){
perror("Error in write() : Unable to write to screen");
exit(-1);
}
// Checking for exit code
if(!strcmp(message, "!\n") && iteration == 1)
{
free(message);
message = NULL;
return NULL;
}
// Freeing message (message is dynamically allocated from receiver)
free(message);
message = NULL;
} while (countMessages(list)!=0);
}
return NULL;
}
void writerSignaller()
{
//Signals the writer, will be called by receiveUDP
pthread_mutex_lock(&writeAvailableCondMutex);
{
pthread_cond_signal(&writeAvailableCond);
}
pthread_mutex_unlock(&writeAvailableCondMutex);
}
void writerInit(List* l){
list = l;
int writingThread = pthread_create(&writerThread, NULL, writeLoop, NULL);
if(writingThread != 0){
perror("write thread failed");
exit(-1);
}
}
void writerCancel()
{
pthread_cancel(writerThread);
}
void writerShutdown()
{
// De-allocating dynamically allocated message if shutdown is called while message is not yet freed
// Note: if we HAVE already freed the pointer, then we've set the message pointer to NULL
// and it is okay to free a NULL pointer (it does nothing)
free(message);
message = NULL;
pthread_join(writerThread, NULL);
}