# Fork does not properly copy POSIX message queue descriptions



## Kallikanzarid (Oct 22, 2013)

Hi! I already asked this question on stackoverflow, but it didn't get any attention, so here it goes.

Is there a way to make FreeBSD copy POSIX message queue descriptions when forking? I know it doesn't by default, because I wrote a test program:


```
#include <stdio.h> #include <stdlib.h> 
#include <sys/types.h> 
#include <unistd.h> 
#include <mqueue.h> 
#include <errno.h> 
#include <fcntl.h>  
int main() {   
   struct mq_attr attrs;
   attrs.mq_maxmsg = 10;
   attrs.mq_msgsize = sizeof(int);
    const char name[] = "/test-queue";
    mqd_t q = mq_open(name, O_CREAT | O_RDWR, 0600, &attrs);
   if (q == (mqd_t)-1) {
     perror("mq_open");
     exit(EXIT_FAILURE);
   }
    mq_unlink(name); // it doesn't matter if I do this at the end or not
    if (fork()) {
     int msg = 666;
     if (mq_send(q, (const char *)&msg, sizeof(msg), 1)) {
       perror("mq_send");
       exit(EXIT_FAILURE);
     }
   } else {
     int msg;
     unsigned priority;
     if (mq_receive(q, (char *)&msg, sizeof(msg), &priority) == -1) {
       perror("mq_receive");
       exit(EXIT_FAILURE);
     }
     printf("%d\n", msg);
   }
    mq_close(q);
    return 0;
}
```
I compiled it under both Linux and FreeBSD 9.2 using `gcc -std=c99 -Wall -o mqtest mqtest.c -lrt`, and under Linux it works. Under FreeBSD I get 
	
	



```
mq_receive: Bad file descriptor
```
 though.


----------



## Kallikanzarid (Oct 22, 2013)

The code apparently suffered when I was pasting it, so here's a better-looking version: http://pastebin.com/Dya0XEhf


----------

