消息队列:msgsnd失败:参数无效:权限被拒绝

时间:2017-06-12 11:45:12

标签: c linux message-queue

i两个通过消息队列进行通信的程序。 每次我无法从客户端程序向服务器程序发送消息,我收到一条错误消息: 无效的参数或权限被拒绝

克林特:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<errno.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/msg.h>
#define MAX_LEN 30

struct msgbuf
{
    long mtype; 
    char mtext[MAX_LEN];
};

int main(int argc, char ** argv)
{
    struct msgbuf message;
    key_t key;
    int msgid;
    if((key = ftok("/tmp", 'e') == -1))
    {
        fprintf(stderr, "ftok() failed\n");
        exit(EXIT_FAILURE);
    }
    if((msgid = msgget(key,0)) == -1)
    {
        perror("msgget failure");
        exit(EXIT_FAILURE);  
    }
    message.mtype = 0;
    fgets(message.mtext, MAX_LEN, stdin);
    if((msgsnd(msgid, &message, strlen(message.mtext) + 1, 0)) == -1)
    {
        perror("msgsnd failed");
        exit(EXIT_FAILURE);
    }
    if((msgrcv(msgid, &message, MAX_LEN,0, MSG_NOERROR)) == -1)
    {
        perror("msgrcv failed");
        exit(EXIT_FAILURE);
    }
    printf("%s", message.mtext);
}

服务器:

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

#define MAX_LEN 60
char* encode(char* string, char* encd_str);

struct msgbuf{
    long mytype; 
    char mtext[MAX_LEN];
};

int main()
{

    struct msgbuf message; // the file is steel decodded.
    key_t key;
    int msgid;
    long type = 0;
    char  encd_str[120];


    if((key = ftok("/tmp", 'e')) == -1)
    {
        fprintf(stderr, "ftok() failed\n");
        exit(EXIT_FAILURE);
    }
    if((msgid = msgget(key,IPC_CREAT | IPC_EXCL |0600)) == -1)
    {
        perror("msgget failure");
        exit(EXIT_FAILURE);  
    }
    while(1)
    {
        if((msgrcv(msgid, &message, MAX_LEN,type, MSG_NOERROR)) == -1)
        {
            perror("msgrcv failed");
            exit(EXIT_FAILURE);
        }

        encode(message.mtext, encd_str);

        if((msgsnd(msgid, &message, strlen(message.mtext) , 0)) == -1)
        {
            perror("msgsnd failed");
            exit(EXIT_FAILURE);
        }

    }

}

char* encode(char* string, char* encd_str)
{
    int i;
    int len = strlen(string);
    for(i =0; i < len; i++)
    {
        encd_str[i*2] = string[i];
        encd_str[i*2 + 1] = 'b';
    }
    encd_str[i*2 +  2]  = '\0';
    return encd_str;
} 

0 个答案:

没有答案