POSIX消息队列,发送和接收

时间:2017-03-25 17:50:14

标签: c++ posix message-queue

我有多个线程使用POSIX消息队列进行通信。

double Pi_Msg(unsigned int p, unsigned int nn)
{
    double *pis = new double[p];
    struct mq_attr attr;
    mqd_t mqdes;
    char buf[256];
    unsigned int prio;
    attr.mq_maxmsg = p;
    attr.mq_msgsize = 256;
    attr.mq_flags = 0;
    mqdes = mq_open("mq", O_RDWR|O_CREAT, 0664, &attr);
    for (unsigned int i = 0; i < p; i++) {
        int pid = fork();
        if (pid < 0) {
            exit(1);
        } else if (pid != 0) {
            wait();
            mq_receive(mqdes, &buf[0], 256, NULL);
            pis[i] = atoi(buf);
        } else {
            double pi = 3.1415;
            char str[128];
            sprintf(str, "%f", pi);
            mq_send(mqdes, str, 128, 0);
            exit(EXIT_SUCCESS);
        }
    }
}

ms_receive总是返回-1,我不知道为什么。

0 个答案:

没有答案