FrontPage|FindPage|TitleIndex|RecentChanges|RSS Message
 

Unix Message Queue #


Sample #

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>

#include <errno.h>

typedef struct
{
    long msg_type;
    char message[BUFSIZ];
}MSG;

MSG msg;

int receiver(key_t msgkey)
{
    int msgid, done = 1;

    msgid = msgget(msgkey, 0666 | IPC_CREAT);

    if (msgid == -1){
        fprintf(stderr, "msgget failed\n");
        exit(EXIT_FAILURE);
    }

    while (done){
        if (msgrcv(msgid, (void *)&msg, BUFSIZ, 0, IPC_NOWAIT) == -1){
            if (errno == ENOMSG) {
                fprintf(stderr, "´õ ÀÌ»ó ¸Þ½ÃÁö°¡ ¾ø½À´Ï´Ù.\n");
            } else {
                fprintf(stderr, "msgrcv ½ÇÆÐ\n");
            }
            exit(EXIT_FAILURE);
        }
        printf("¹ÞÀº ¸Þ½ÃÁö: %s", msg.message);

        if (strncmp(msg.message, ".", 1) == 0){
            done = 0;
        }
    }

    if (msgctl(msgid, IPC_RMID, 0) == -1){
        fprintf(stderr, "msgctl(IPC_RMID) failed\n");
        exit(EXIT_FAILURE);
    }
    printf("\n¸Þ½ÃÁö ¼ö½ÅÀ» Á¾·áÇÕ´Ï´Ù.\n\n");
    exit(EXIT_SUCCESS);
}

int sender(key_t msgkey)
{
    int msgid, done = 1;
    char buffer[BUFSIZ];

    msgid =msgget(msgkey, 0666 | IPC_CREAT);

    if (msgid == -1){
        fprintf(stderr, "msgget failed\n");
        exit(EXIT_FAILURE);
    }

    printf("Àü¼ÛÇÒ ¸Þ½ÃÁö¸¦ ÀÔ·ÂÇϼ¼¿ä.\n");
    printf("¸Þ½ÃÁö ÀÔ·Â Á¾·á´Â ùĭ¿¡ '.'¸¦ ÀÔ·ÂÇϼ¼¿ä.\n\n");

    while (done) {
        printf("Àü¼ÛÇÒ ¸Þ½ÃÁö: ");
        fgets(buffer, BUFSIZ, stdin);
        msg.msg_type = 1;
        strcpy(msg.message, buffer);

        if (msgsnd(msgid, (void *)&msg, BUFSIZ, 0) == -1){
            fprintf(stderr, "msgsnd failed\n");
            exit(EXIT_FAILURE);
        }

        if (strncmp(buffer, ".", 1) == 0){
            done = 0;
        }
    }
    printf("\n¸Þ½ÃÁö Àü¼ÛÀ» Á¾·áÇÕ´Ï´Ù.\n\n");
    exit(EXIT_SUCCESS);
}

int main(int argc, char *argv[])
{
    key_t key;

    key = ftok(".", 'M');
    if (argc > 1) receiver(key);
    else    sender(key);
}


Ãâó : http://blog.naver.com/eggkorea92/40003492319

last modified 2007-01-09 18:05:05
EditText|FindPage|DeletePage|LikePages|