基本的unix服务器 - 客户端IPC(msg队列)问题

时间:2012-06-06 20:14:28

标签: c unix client ipc

我正在研究一个问题,它意味着一个基本运行的服务器客户端(之前完成)。问题是我运行服务器而不是运行客户端。我创建了我的消息队列,在客户端接受我的字符输入发送它时,我得到确认打印,但我的服务器msgrcv没有响应。

皮下

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

#include "struc.h"


int main(){
    int qt;
    struct msg m;

    qt = msgget(1271,IPC_CREAT|IPC_EXCL|0600);
    if(qt < 0){ perror("Error MSGGET()\n");}
    printf("msg queue created!\n");

    if(msgrcv(qt,&m,sizeof(struct msg),0,0)<0){
        perror("Msg recive error");
    }   
    printf("msg recived!\n");


    msgctl(qt,IPC_RMID,NULL);
    return 0;
}

C.C

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

#include "struc.h"

int main(){
    int qt;
    struct msg m;
    qt = msgget(1271,0);
    if(qt < 0){ perror("~~~ Error MSGGET()\n");}
    printf("msg created!\n");

    printf("Enter one char: !\n");
    scanf("%c",&m.c);

    msgsnd(qt, &m,sizeof(struct msg),0);
    printf("msg sent!\n");
return 0;
}

struc.h

struct msg{
    long mtype;
//  matrix M;
    char c;
};

(通过创建3个文件,你自己测试它。欢迎任何想法,也许我错过了一些东西)

1 个答案:

答案 0 :(得分:1)

您应该这样做以验证发送不会失败。

 if(msgsnd(qt, &m,sizeof(struct msg),0)) < 0) {
    perror("Msg send error");
  }

您还应该注意msgsnd的文档:

The msgp argument is a pointer to caller-defined structure of the 
following general form:

       struct msgbuf {
           long mtype;       /* message type, must be > 0 */
           char mtext[1];    /* message data */
        };

也就是说,您必须在发送的邮件中设置mtype为&gt; 0.目前它尚未初始化,所以你应该这样做:

m.mtype = 1;
if(msgsnd(qt, &m,sizeof(struct msg),0)) < 0) {
   perror("Msg send error");
}