-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathleitor.c~
129 lines (100 loc) · 2.15 KB
/
leitor.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
#include <stdio.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>
#include <sys/shm.h>
#include <sys/sem.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 show_to_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 ( 0x002, 0600 | IPC_CREAT );
while(1) {
status = msgrcv( msg_id, &msg, sizeof(msg.text), 1, 0);
printf ("%s", msg.text);
if(strcmp(msg.text, fim) == 0)
{
break;
}
}
}
void get_from_shm(int sem_id)
{
int msg_id;
int status;
int count;
int last_position_readed = -1;
char fim[] = "FIM\n";
MsgStruct msg;
ArrayMsg *messages;
// Creates the shared memory and the queue of messages.
shm_id = shmget(0x4321, sizeof(ArrayMsg), IPC_CREAT | 0666);
msg_id = msgget ( 0x002, 0600 | IPC_CREAT );
// Pointing to the shared memory.
messages = (ArrayMsg *) shmat(shm_id, NULL, 0);
while(1)
{
// Entra na região crítica, travando o mutex.
semop(sem_id, g_lock_sembuf, 1);
count = (*messages).position;
while (last_position_readed <= count)
{
msg = (*messages).msgs[last_position_readed];
status = msgsnd( msg_id, &msg, sizeof(msg.text), 0);
last_position_readed++;
}
// Sai da região crítica, liberando o mutex
semop(sem_id, g_unlock_sembuf, 1);
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 o semáforo
sem_id = semget(SEM_KEY, 1, IPC_CREAT | 0666);
pid = fork();
if(pid > 0)
{
show_to_user(pid);
kill(pid, 9);
}
else if (pid == 0)
{
printf("aqui");
get_from_shm(sem_id);
} else {
printf("Erro no Fork!\n");
}
shmctl(shm_id, IPC_RMID, NULL);
return 0;
}