본문 바로가기
IT/C++.C

리눅스에서 message queue를 사용하는 프로그램을 이벤트 드리븐 방식으로 구현

by 골든크랩 2025. 1. 2.
728x90
반응형

 

리눅스에서 message queue를 사용하는 프로그램을 이벤트 드리븐 방식으로 구현할 수 있습니다. 이벤트 드리븐 방식은 자원을 효율적으로 사용하면서 message queue에 값이 들어왔을 때만 처리를 수행하도록 할 수 있어요. 이를 위해 select나 epoll 같은 시스템 콜을 사용할 수 있습니다.

 

이 코드는 epoll을 사용하여 message queue에 새로운 메시지가 들어왔을 때만 처리를 수행합니다. 이 방식은 메시지가 없을 때는 CPU 자원을 거의 사용하지 않으므로 성능 면에서도 유리합니다.

 

아래는 epoll을 사용하는 예제입니다:

 

#include <sys/epoll.h>
#include <sys/msg.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

#define MSG_QUEUE_KEY 1234
#define MAX_EVENTS 10

struct msgbuf {
    long mtype;
    char mtext[100];
};

int main() {
    int msqid, epfd;
    struct epoll_event ev, events[MAX_EVENTS];
    struct msgbuf msg;
    
    // Message queue 생성
    if ((msqid = msgget(MSG_QUEUE_KEY, IPC_CREAT | 0666)) == -1) {
        perror("msgget");
        exit(EXIT_FAILURE);
    }

    // epoll 인스턴스 생성
    if ((epfd = epoll_create1(0)) == -1) {
        perror("epoll_create1");
        exit(EXIT_FAILURE);
    }

    ev.events = EPOLLIN;
    ev.data.fd = msqid;

    // epoll에 message queue 등록
    if (epoll_ctl(epfd, EPOLL_CTL_ADD, msqid, &ev) == -1) {
        perror("epoll_ctl");
        exit(EXIT_FAILURE);
    }

    while (1) {
        int nfds = epoll_wait(epfd, events, MAX_EVENTS, -1);
        for (int n = 0; n < nfds; ++n) {
            if (events[n].events & EPOLLIN) {
                if (msgrcv(events[n].data.fd, &msg, sizeof(msg.mtext), 0, 0) == -1) {
                    perror("msgrcv");
                    exit(EXIT_FAILURE);
                }
                printf("Received message: %s\n", msg.mtext);
            }
        }
    }

    close(epfd);
    return 0;
}

 

 

728x90
반응형

댓글