-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprocess_3.c
More file actions
100 lines (94 loc) · 2.72 KB
/
process_3.c
File metadata and controls
100 lines (94 loc) · 2.72 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
#include "process_3.h"
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include "constants.h"
#include <signal.h>
#include <semaphore.h>
#include <fcntl.h>
#include <sys/mman.h>
extern SharedData *shmPtr;
static void SetupSignals()
{
sigset_t signals;
sigfillset(&signals);
sigprocmask(SIG_BLOCK, &signals, NULL);
}
void process3(int pipe_p2_write, int pipe_p1_read, sem_t *sem_parent_to_p3, sem_t *sem_p3_to_p2, int shmId)
{
SetupSignals();
shmPtr = mmap(0, sizeof(SharedData), PROT_WRITE | PROT_READ, MAP_SHARED, shmId, 0);
if (!shmPtr)
{
printf("Failed to create shmPtr\n");
exit(1);
}
int choice;
int shouldSkip = 0;
while (1)
{
if (!shouldSkip)
{
scanf("%d", &choice);
while (getchar() != '\n');
if (choice == 1)
{
fflush(stdout);
char buf[MAX_TEXT_SIZE];
fgets(buf, MAX_TEXT_SIZE, stdin);
if (write(pipe_p2_write, buf, strlen(buf)) < 0)
{
printf("Failed to write data using pipe to p2\n");
exit(1);
}
printf("P3(%d): Sent data via pipe to p2\n", getpid());
fflush(stdout);
}
else if (choice == 2)
{
FILE *file = fopen("input.txt", "r");
if (!file)
{
printf("Failed to open input.txt\n");
exit(1);
}
char buf[MAX_TEXT_SIZE];
while (fgets(buf, MAX_TEXT_SIZE, file))
{
int len = strlen(buf);
if (write(pipe_p2_write, buf, len + 1) < 0)
{
printf("Failed to write data using pipe to p2\n");
fclose(file);
exit(1);
}
printf("P3(%d): Sent data via pipe to p2\n", getpid());
fflush(stdout);
}
fclose(file);
}
else
{
printf("Invalid choice. Enter 1 or 2.\n");
}
}
if (sem_trywait(sem_parent_to_p3) == 0)
{
sem_post(sem_p3_to_p2);
if (shmPtr->signum == SIGTERM)
{
printf("P3(%i): received signal %i\n", getpid(), shmPtr->signum);
break;
}
else if (shmPtr->signum == SIGTSTP)
{
shouldSkip = 1;
}
else if (shmPtr->signum == SIGCONT)
{
shouldSkip = 0;
}
}
}
}