-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathwrite.c
104 lines (80 loc) · 2.69 KB
/
write.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
#include <stdlib.h>
#include <stdio.h>
#include <signal.h> // signal handler
#include <unistd.h>
#include <sys/types.h> // system calls
#include <sys/stat.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include "common.h"
void keyboard_interrupt(int signalNumber);
char *get_user_input(void);
void call_status(int functionCall, char *message);
messageType *sharedMemoryPointer;
int main(void)
{
// handling keyboard-interruption ctrl-c
signal(SIGINT, keyboard_interrupt);
// generate a unique key
key_t key;
call_status(key = ftok("./src/read.c", 65), "Unique key failed\n");
// create shared memory segment
int sharedMemoryID;
call_status(sharedMemoryID = shmget(key, sizeof(messageType), SHARED_MEM_OPTIONS), "writer: unable to get shared memory\n");
// attach this file to shared memory segment
call_status(((sharedMemoryPointer = shmat(sharedMemoryID, 0, 0)) == (void *) -1), "writer: Unable to attach\n");
// writer goes first
(*sharedMemoryPointer).turn = WRITER_TURN;
// cleared cleanup flag allows program to continue
(*sharedMemoryPointer).cleanup = 0;
while(!(*sharedMemoryPointer).cleanup)
{
if ((*sharedMemoryPointer).turn == WRITER_TURN)
{
strcpy((*sharedMemoryPointer).message, get_user_input()) ;
(*sharedMemoryPointer).turn = READER_TURN;
}
}
// detach from shared memory segment
call_status(shmdt(sharedMemoryPointer), "writer: unable to detach\n");
// destroy shared memory segment
call_status(shmctl(sharedMemoryID, IPC_RMID, 0), "writer: unable to deallocate\n");
return 0;
}
char *get_user_input(void)
{
char buffer[TEXT_SIZE];
char *userInput = malloc(strlen(buffer) + 1);
fputs("\n[writer] - enter a message: ", stdout);
fgets(buffer, sizeof(buffer), stdin);
// handling "quit" from user input
call_status((strcmp(buffer, "quit\n") == 0) * -1, " ");
buffer[strlen(buffer) - 1] = '\0';
return strcpy(userInput, buffer);
}
void keyboard_interrupt(int signalNumber)
{
printf(" received. Terminating program...\n");
// cleanup flag set HIGH allows reader to clean up
(*sharedMemoryPointer).cleanup = 1;
// detach from shared memory segment
call_status(shmdt(sharedMemoryPointer), "writer: unable to detach\n");
exit(EXIT_SUCCESS);
}
void call_status(int functionCall, char *message)
{
if (functionCall < 0)
{
if (strcmp(message, " ") == 0)
{
// cleanup flag set HIGH allows reader to clean up
(*sharedMemoryPointer).cleanup = 1;
exit(EXIT_SUCCESS);
}
else
{
perror(message);
exit(EXIT_FAILURE);
}
}
}