-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathescritor.c~
130 lines (102 loc) · 2.25 KB
/
escritor.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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
#include <stdio.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>
#include <sys/shm.h>
#include <sys/sem.h>
#include <unistd.h>
struct sembuf g_lock_sembuf[1];
struct sembuf g_unlock_sembuf[1];
#define SEM_KEY 0x1111
int shm_id;
typedef struct
{
long int type;
char text[250];
} MsgStruct;
typedef struct
{
MsgStruct msgs[9999];
int position;
} ArrayMsg;
void read_from_user(int pid)
{
MsgStruct msg;
int status;
int msg_id;
char fim[] = "FIM\n";
msg.type = 1;
// ligar à fila de mensagens. A key deve ser hexadecimal.
msg_id = msgget ( 0x001, 0600 | IPC_CREAT );
while(1)
{
printf("Digite a mensagem: ");
fgets(msg.text, 250, stdin);
printf ("Mensagem enviada!\n");
status = msgsnd( msg_id, &msg, sizeof(msg.text), 0);
if(strcmp(msg.text, fim)==0)
{
break;
}
}
}
void send_to_reader(int sem_id)
{
int msg_id;
int status;
int count = 0;
MsgStruct msg;
ArrayMsg *messages;
char fim[] = "FIM\n";
// Cria a memória compartilhada e a fila de mensages
shm_id = shmget(0x4321, sizeof(ArrayMsg), IPC_CREAT | 0666);
msg_id = msgget ( 0x001, 0600 | IPC_CREAT );
// Aponta para a memória comppatilhada
messages = (ArrayMsg *) shmat(shm_id, NULL, 0);
while(1)
{
// receber uma mensagem (bloqueia se não houver)
status = msgrcv( msg_id, &msg, sizeof(msg.text), 1, 0);
// Entra na região crítica, travando o mutex.
semop (sem_id, g_lock_sembuf, 1);
(*messages).msgs[count] = msg;
(*messages).position = count;
// Sai da região crítica, liberando o mutex
semop (sem_id, g_unlock_sembuf, 1);
count++;
if(strcmp(msg.text, fim)==0)
{
break;
}
}
}
int main()
{
int pid;
int sem_id;
// Inicializa estrutras de controle do semaforo
g_lock_sembuf[0].sem_num = 0;
g_lock_sembuf[0].sem_op = -1;
g_lock_sembuf[0].sem_flg = 0;
g_unlock_sembuf[0].sem_num = 0;
g_unlock_sembuf[0].sem_op = 1;
g_unlock_sembuf[0].sem_flg = 0;
// Cria e Inicializa o semáforo. O mutex comeca aberto.
sem_id = semget(SEM_KEY, 1, IPC_CREAT | 0666);
semop (sem_id, g_unlock_sembuf, 1);
pid = fork();
if (pid > 0)
{
read_from_user(pid);
}
else if (pid == 0)
{
send_to_reader(sem_id);
}
else
{
printf("Erro no fork!");
}
shmctl(shm_id, IPC_RMID, NULL);
return 0;
}