2011-03-14 7 views
1

친애하는 친구, msgrcv가 빈 버퍼를 수신하는 이유는 무엇입니까? 여기 UNIX 메시지 큐 msgrcv가 메시지를받지 못했습니다.

코드입니다 :

enter code here 
#include <sys/msg.h> 
#include <unistd.h> 
#include <sys/types.h> 
#include <stdio.h> 
#include <string.h> 

typedef struct mymsg { 
    long mtype; 
    char mtext[24]; 
}mymsg; 

int main() 
{ 
    int msqid; 
    mymsg msg,buff; 
    msqid=msgget(IPC_PRIVATE,IPC_CREAT|IPC_EXCL); 

    if(msqid==-1){ 
    perror("FAiled to create message queue\n"); 
    } 
    else{ 
    printf("Message queue id:%u\n",msqid); 
    } 
    msg.mtype=1; 
    strcpy(msg.mtext,"This is a message"); 
    if(msgsnd(msqid,&msg,sizeof(msg.mtext),0)==-1){ 
    perror("msgsnd failed:"); 
    } 
    else{ 
    printf("Message sent successfully\n"); 
    } 
//ssize_t msgrcv(int msqid, void *msgp, size_t msgsz, long msgtyp,int msgflg); 

    // msgrcv(msqid,buff.mtext,sizeof(msg.mtext),1,0); This was error 
    msgrcv(msqid,&buff,sizeof(msg.mtext),1,0); // This is correct (Thanks to Erik) 
    printf("The message received is: %s\n",buff.mtext); 
} 

    Output: 
    [[email protected] message_queue]# ./a.out 
    Message queue id:294919 
    Message sent successfully 
    The message received is: 
                1,1   Top 

답변

6

msgbuf.mtype 1로 설정해야합니다 - 당신은 당신이 1

또는 유형의 메시지를 원하는 msgrcv을 이야기하고 있기 때문에, 당신은 어떤 긍정적으로 msgbuf.mtype을 설정할 수 있습니다 값을 입력 한 다음 msgtyp 인수로 0을 전달하여 메시지 유형을 원한다고 msgrcv에게 알리십시오.

msgrcv(msqid,&buff,sizeof(msg.mtext),1,0); 

EDIT :

또한 msgrcvmsgbuf 포인터 기대 테스트 작업 소스 :

#include <sys/msg.h> 
#include <unistd.h> 
#include <sys/types.h> 
#include <stdio.h> 
#include <string.h> 

typedef struct mymsg { 
    long mtype; 
    char mtext[24]; 
}mymsg; 

int main() 
{ 
    int msqid; 
    mymsg msg,buff; 
    msqid=msgget(IPC_PRIVATE,IPC_CREAT|IPC_EXCL); 

    if(msqid==-1){ 
    perror("FAiled to create message queue\n"); 
    } 
    else{ 
    printf("Message queue id:%u\n",msqid); 
    } 
    msg.mtype=1; // was there failed to copy 
    strcpy(msg.mtext,"This is a message"); 
    if(msgsnd(msqid,&msg,sizeof(msg.mtext),0)==-1){ 
    perror("msgsnd failed:"); 
    } 
    else{ 
    printf("Message sent successfully\n"); 
    } 
//ssize_t msgrcv(int msqid, void *msgp, size_t msgsz, long msgtyp,int msgflg); 

    msgrcv(msqid,&buff,sizeof(msg.mtext),1,0); 
    printf("The message received is: %s\n",buff.mtext); 
} 
+0

죄송합니다 라인 : msg.mtype = 1; 이미 거기에 있었다, 나는 그것을 모방하는 것을 놓쳤다. 그러나 여전히 작동하지 않습니다. 가능하다면 – kingsmasher1

+0

도와주세요. – kingsmasher1

+0

@ kingsmasher1 : 업데이트 된 답변 – Erik