martedì 26 luglio 2011

An mqueue example that actually works

As for title, i couldn't find an example of a simple application using POSIX mqueues that could work under ubuntu 11.04. There are mainly 2 problems:

  • Queue names must begin with a "/"
  • When you set the flag O_CREAT you MUST supply an mq_attr structure to the constructor.
  • The mq_attr structure parameters must (obviuosly) fit your system constraints

So, here's a slightly different mqueue send example



#define PMODE 0666
#define MSGSIZE 256

int main (){
      int i;
      int md;
      int status;
      struct mq_attr attr;
      mqd_t mqfd;

     attr.mq_maxmsg = 10;
     attr.mq_msgsize = MSGSIZE;
     attr.mq_flags   = 0;
      mqfd = mq_open ("/my_queue3", O_WRONLY|O_CREAT,PMODE,&attr);
      if (mqfd == -1)
        {
          perror("couldn't open mqueue");
          exit(0);
        };

   for (i=0; i<10 data-blogger-escaped-br="" data-blogger-escaped-i="">    {
    status = mq_send(mqfd,"ciao",4,0);
    if (status == -1){
        perror("mq_send failure on mqfd");
    }
    else{
        printf("successful send, i = %d\n",i);
    }
    }

}