버퍼를 공유메모리로 설정하고 접근할때 질문있습니다.
글쓴이: kangmaee / 작성시간: 수, 2014/02/26 - 1:12오후
헤더
#ifndef QUEUE_H #define QUEUE_H typedef struct tagNode { char data[1400]; } Node; typedef struct tagCircularQueue { int capacity; int front; int rear; Node* nodes; } CircularQueue; void CreateQueue(CircularQueue** queue, int capacity); void DestroyQueue(CircularQueue* queue); void Enqueue(CircularQueue* queue, char data[1400]); char *Dequeue(CircularQueue* queue); int GetSize(CircularQueue* queue); int IsEmpty(CircularQueue* queue); int IsFull(CircularQueue* queue); #endif
라이브러리
#include "queue.h" #include <stdio.h> #include <stdlib.h> #include <sys/shm.h> #include <sys/ipc.h> #include <unistd.h> #include <fcntl.h> #include <string.h> #define SHARED_MEMORY_KEY 9876 int shmid; void *shm_addr = (void *)0; Node *data; void CreateQueue(CircularQueue** queue, int capacity) { *queue = (CircularQueue*)malloc(sizeof(CircularQueue)); (*queue)->nodes = (Node*)malloc(sizeof(Node)* (capacity + 1)); (*queue)->capacity = capacity; (*queue)->front = 0; (*queue)->rear = 0; shmid = shmget((key_t)SHARED_MEMORY_KEY, sizeof(CircularQueue), 0666|IPC_CREAT); if(shmid == -1) { perror("shmget failed : "); exit(0); } printf("shmid = %d\n", shmid); shm_addr = shmat(shmid, (void *)0, 0); if(shm_addr == (void *)-1) { perror("shmat failed : "); exit(0); } data = (Node *)shm_addr; } void DestroyQueue(CircularQueue* queue) { if(shmdt(shmid) == -1) { perror("shmdt failed : "); exit(0); } free(queue->nodes); free(queue); } void Enqueue(CircularQueue* queue, char data[1400]) { int position = 0; if (queue->rear == queue->capacity + 1) { queue->rear = 0; position = 0; } else position = queue->rear++; strcpy(queue->nodes[position].data, data); } char *Dequeue(CircularQueue* queue) { int position = queue->front; shmat(shmid, (void *)0, 0); if (position == queue->capacity) queue->front = 0; else queue->front++; return queue->nodes[position].data; } int GetSize(CircularQueue* queue) { if (queue->front <= queue->rear) return queue->rear - queue->front; else return (queue->capacity + 1 - queue->front) + queue->rear; } int IsEmpty(CircularQueue* queue) { return (queue->front == queue->rear); } int IsFull(CircularQueue* queue) { if (queue->front < queue->rear) return (queue->rear - queue->front) == queue->capacity; else return (queue->rear + 1) == queue->front; }
메인 1(버퍼삽입)
#include "queue.h" #include <stdio.h> #include <stdlib.h> int main(void) { CircularQueue* queue; CreateQueue(&queue, 100); Enqueue(queue, "abcd"); Enqueue(queue, "dcba"); return 0; }
메인 2(버퍼 내용 꺼내기)
#include "queue.h" #include <stdio.h> int main(void) { CircularQueue* queue; CreateQueue(&queue, 100); printf("data : "); printf("%s\n", Dequeue(queue)); printf("%s\n", Dequeue(queue));
이렇게 해놓고 메인1을 실행하고 메인2를 실행하면 아무 자료가 출력되지 않습니다.
ipcs로 확인해보면 같은 메모리로 잡힌거로 보이는데..어디가 잘못된건지 도무지 모르겠네요
Forums:
메인 1 메인 2 에 선언된 큐는 서로 다릅니다
입문서 참고하세요
1년차 임베디드 소프트쟁이 입니다
시스템에 관심이 많습니다
댓글 달기