By liran bh | 5/16/2016 | Linux User Space

SYS V mailbox

Header file


#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <errno.h>
#define MSG_KEY 40
#define MSG_MODE (IPC_EXCL | 0777)
/* use of 'IPC_DIPC' is the ONLY thing that makes 
 * this program a distributed * one. Everything 
 * else is normal System V IPC programming */
#define MSG_TYPE 10
#define MSG_SIZE 512
struct message
{
   long mtype;
   char mtext[MSG_SIZE];
};

Receiver 

#include "msgq.h"
int main()
{
   int msgid;
   struct message mess;
 
   /* create the message queue. The other 
        * process will access it later */
   msgid = msgget(MSG_KEY, MSG_MODE | IPC_CREAT );
 
   if(msgid < 0) 
   {
      fprintf(stderr,"Hello1: msgget() failed BECAUSE %s\n", strerror(errno));
      exit(20);
   }
   fprintf(stderr,"Hello1: waiting to receive a message.\n");
 
   if(msgrcv(msgid, (struct msgbuf *)&mess, sizeof(mess.mtext), 0, 0) < 0)
      fprintf(stderr,"Hello1: msgrcv() failed BECAUSE %s\n", strerror(errno));
   else 
      fprintf(stderr,"Hello1: Received '%s'\n",mess.mtext); 
 
   msgctl(msgid,IPC_RMID,NULL); 
   exit(0);
}

Sender

#include "msgq.h"
int main()
{
   int msgid;
   struct message mess;
   /* gain access to the message queue that was
    * created by hello1 */
   msgid = msgget(MSG_KEY, MSG_MODE);
   if(msgid < 0) 
   {
      fprintf(stderr,"Hello2: msgget() failed BECAUSE %s\n",strerror(errno));
      exit(20);
   }
   mess.mtype = MSG_TYPE; /* not used here */
   strcpy(mess.mtext,"Hello, Distributed Programming!");
   /* now send the message. This will traverse 
    * the network if hello1 and hello2 programs 
    * are in different computers and DIPC is 
    * properly installed */
   if(msgsnd(msgid, (struct msgbuf *)&mess, sizeof(mess.mtext), 0) < 0)
   {
      fprintf(stderr,"Hello2: msgsnd() failed BECAUSE %s\n", strerror(errno));
      exit(20);
   }
   exit(0);
}

 

{{CommentsModel.TotalCount}} Comments

Your Comment

{{CommentsModel.Message}}

Recent Stories

Top DiscoverSDK Experts

User photo
3355
Ashton Torrence
Web and Windows developer
GUI | Web and 11 more
View Profile
User photo
3220
Mendy Bennett
Experienced with Ad network & Ad servers.
Mobile | Ad Networks and 1 more
View Profile
User photo
3060
Karen Fitzgerald
7 years in Cross-Platform development.
Mobile | Cross Platform Frameworks
View Profile
Show All
X

Compare Products

Select up to three two products to compare by clicking on the compare icon () of each product.

{{compareToolModel.Error}}

Now comparing:

{{product.ProductName | createSubstring:25}} X
Compare Now