23.12.03 최초 작성
/system/shared_memory.h
: 센서 값을 저장하는 구조체와 공유 메모리의 IPC key
가 정의된 파일#ifndef _SHARED_MEMORY_H
#define _SHARED_MEMORY_H
enum def_shm_key {
SHM_KEY_BASE=10,
SHM_KEY_SENSOR = SHM_KEY_BASE,
SHM_KEY_MAX
};
typedef struct shm_sensor {
int temp;
int press;
int humidity;
} shm_sensor_t;
extern int shm_id[SHM_KEY_MAX - SHM_KEY_BASE];
#endif /* _SHARED_MEMORY_H */
/system/system_server.c
: 공유 메모리로부터 센서 값을 읽어 이를 모니터에 출력하는 코드 추가#define SENSOR_DATA 1
#include <sys/ipc.h>
#include <sys/shm.h>
#include <shared_memory.h>
...
static shm_sensor_t *the_sensor_info = NULL;
...
void *monitor_thread(){
printf("Monitor thread started!\n");
toy_msg_t msg;
int shmid;
struct shmesg *shmp;
while(1){
if(mq_receive(monitor_queue, (void *)&msg, sizeof(toy_msg_t), 0) < 0){
perror("Message queue recevie error : monitor");
exit(0);
}
printf("Monitor msq arrived\n");
print_msq(&msg);
// 메시지 큐로부터 메시지 수신하면 공유 메모리로부터 값을 읽어 모니터에 출력
if (msg.msg_type == SENSOR_DATA) {
shmid = msg.param1;
the_sensor_info = (shm_sensor_t *)shmat(shmid, NULL, SHM_RDONLY);
if(shmp < 0){
perror("shmat failed : monitor thread");
exit(0);
}
printf("temp: %d\n", the_sensor_info->temp);
printf("info: %d\n", the_sensor_info->press);
printf("humidity: %d\n", the_sensor_info->humidity);
}
}
}
/ui/input.c
: 5초 마다 메시지 큐에 메시지를 저장해 모니터 스레드가 센서 값을 출력하게 함#include <sys/ipc.h>
#include <sys/shm.h>
#include <shared_memory.h>
...
static shm_sensor_t *the_sensor_info = NULL;
int shmid;
struct shmseg *shmp;
...
int input()
{
...
// 공유 메모리 매핑
shmid = shmget(SHM_KEY_SENSOR, sizeof(shm_sensor_t), IPC_CREAT | 0777);
if (shmid < 0){
perror("shmget failed : sensor thread");
exit(0);
}
the_sensor_info = (shm_sensor_t *)shmat(shmid, NULL, 0);
if (shmp < 0){
perror("shmat failed : sensor thread");
exit(0);
}
...
}
...
//5초마다 monitor_queue에 메시지를 보내 센서 값을 출력하게 함
void *sensor_thread(void* arg)
{
char *s = arg;
toy_msg_t msg;
int mqretcode;
printf("%s", s);
the_sensor_info->temp = 1;
the_sensor_info->press = 2;
the_sensor_info->humidity = 4;
while (1) {
sleep(5);
posix_sleep_ms(5, 0);
msg.msg_type = 1;
msg.param1 = shmid;
msg.param2 = 0;
mqretcode = mq_send(monitor_queue, (char *)&msg, sizeof(msg), 0);
assert(mqretcode == 0);
}
return 0;