在C中使用消息队列时获得“错误的系统调用(核心转储)”

时间:2014-12-09 21:39:55

标签: c message-queue

我正在尝试做一个涉及消息队列的作业,当我尝试做任何事情时我都会收到“糟糕的系统调用(核心转储)”,我不知道为什么。此外,当我使用get_queue_ds()函数时,它不会为我编译,但我认为这是因为我在Windows上使用cygwin。任何帮助将不胜感激或链接到类似的代码(搜索这样的东西不会产生任何结果)。谢谢。

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>

#define MAX_SEND_SIZE 1024//Make sure I have comments

typedef struct mymsgbuf
{
    long mtype;                 /* type of message */
    long sender_id;             /* sender identifier */
    char msg[MAX_SEND_SIZE];    /* content of message */
}MSGBUFFER;


/* Function prototypes */
void send_message(int qid, MSGBUFFER *qbuf, long type, char *text);
void read_message(int qid, MSGBUFFER *qbuf, long type);
void remove_queue(int qid);
void change_queue_mode(int qid, char *mode);
void usage(void);

int main(int argc, char *argv[])
{
    key_t myKey;
    int   msgqueue_id;
    int qid;
    MSGBUFFER* qbuf;

    if(argc == 1)
        usage();
    else            
        myKey = ftok("/cis370/lab5", 1);//Creates a unique key

    //Opens message queue
    qid = msgget(myKey, IPC_CREAT | 0660);
    if(qid == -1)
    {
        printf("Creating message queue failed");
        exit(1);
    }

    switch(tolower(argv[1][0]))
    {
        case 's': send_message(qid, qbuf, MAX_SEND_SIZE, argv[2]);
                  break;
        case 'r': read_message(qid, qbuf, MAX_SEND_SIZE);
                  break;
        case 'd': remove_queue(qid);
                  break;
        case 'm': change_queue_mode(qid, argv[2]);
                  break;
        default: usage();
    }
    return(0);
}


void send_message(int qid, MSGBUFFER *qbuf, long type, char *text)
{
    int length, result;
    length = sizeof (MSGBUFFER) - sizeof (long);
    result = msgsnd(qid, (MSGBUFFER *)qbuf, length, 0);
    if (result == -1)
    {
        printf("Send message failed\n");
    }

}


void read_message(int qid, MSGBUFFER *qbuf, long type)
{
    int result, length;
    length = sizeof (MSGBUFFER) - sizeof (long);
    result = msgrcv(qid, (MSGBUFFER*)qbuf, length, type, 0);
    if (result == -1)
    {
        printf("Messege read failed\n");
    }
}


void remove_queue(int qid)
{
    int result;
    result = msgctl(qid, IPC_STAT, 0);
    if (result == -1)
    {
        printf("Queue removal failed");
    }

}



void change_queue_mode(int qid, char *mode)
{
    /*struct msqid_ds tmpbuf;
    int result;
    //isn't working on cygwin
    //get_queue_ds(qid, &tmpbuf);

    sscanf(mode, "%ho", &tmpbuf.msg_perm.mode);

    result = msgctl(qid, IPC_SET, &tmpbuf);
    if (result == -1)
    {
        printf("Queue mode change failed");
    }*/

}


void usage(void)
{
    printf("USAGE:\tmsgqueue\t(s)end  <type>  <message>\n");
    printf("\t\t\t(r)ecv  <type> \n");
    printf("\t\t\t(d)elete\n");
    printf("\t\t\t(m)ode  <mode>\n");

    exit(0);
}

1 个答案:

答案 0 :(得分:1)

Cygwin使用特殊的后台服务来实现持久的XSI IPC。查看Cygserver的文档,了解如何配置和启动它。