Tuesday, March 22, 2016

Linux IPC the Message Queue

Linux IPC Message Queue is inter process/thread exchanging message as you choose.
This examples are made two programs.

rcvmsg.c
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>

main()
{
    int msqid;
    key_t msgkey;
    struct msgbuf{
        long mtype;
        char mdata[256];
    };
    struct msgbuf msgdata,*p;

    p = &msgdata;
    // Make Message queue key.
    msgkey = ftok("msgq.key",'X');
    // Get Message queue ID.
    msqid = msgget(msgkey,IPC_CREAT|0666);

    // Message receive loop wile get "END" massage.
    while(1)
    {
        // Receive a Message.
        if(msgrcv(msqid,p,sizeof(p->mdata),0,IPC_NOWAIT)<=0) {
            printf("No message\n");
            sleep(3);
            continue;
        }
        printf("message received from %ld\n%s\n",p->mtype,p->mdata);
        if(strncmp((char*)p->mdata, "END", (size_t)3)==0)
            break;
    }

    // Remove Message Queue
    msgctl(msqid, IPC_RMID, 0);
}

"rcvmsg" functions.
   1. Create message queue.
   2. Waiting receive a message. It continue until "END" receiving.
   3. Remove message queue.

sndmsg.c
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>

main()
{
    int msqid;
    key_t msgkey;
    struct msgbuf{
        long mtype;
        char mdata[256];
    };
    struct msgbuf msgdata,*p;

    // Make Message queue key.
    msgkey = ftok(argv[1], 'X');
    // Get Message queue ID. (Only get existing message queue.)
    msqid = msgget(msgkey, 0666);
    printf("QID = %d\n", msqid);
    if(msqid<0) return;

    p = &msgdata;
    printf("Enter message: ");
    fflush(stdin);
    fgets(p->mdata,BUFSIZ,stdin);
    p->gtmtype = getpid();
    // Message send.
    msgsnd(msqid,p,sizeof(p->data),0);

}
"sndmsg" functions.
   1. Create message queue. If message queue don't exist then quit self.
   2. Wait user input message.
   3. Send a message.

"rcvmsg" run at first then late run "sndmsg".
"sndmsg" send "END" message when "rcvmsg" is going to final.


No comments:

Post a Comment