空白的msgrcv缓冲区

时间:2014-04-01 17:26:06

标签: c message-queue

我尝试在调用者和接收者之间运行电话会话的消息队列程序,并在此处给出更正。我继续得到以下结果:

 ./caller
 Caller Program
 <<<
 CALLER:Hello!!

在运行调用者可执行文件时。接收时的消息缓冲区为空。我不知道为什么。请帮助!!

caller.c是:

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

struct msgbuf
{
long mtype;
char mtext[140];
}msg_buf;

int send_msg_id,receive_msg_id;
key_t send_key,receive_key;

void *send_message(void *a)
{
send_key=ftok("Caller1.c",'A');
if (send_key==-1)
{
    printf("\nCaller send key error");
    exit(1);
}
send_msg_id=msgget(send_key,0666 | IPC_CREAT);
if (send_msg_id==-1)
{   
    printf("\nCaller send msgget error");
    exit(1);
}
printf("\nCALLER:");
while (fgets(msg_buf.mtext,sizeof(msg_buf.mtext),stdin)!=NULL)
{
    msg_buf.mtype=1;
    int len=strlen(msg_buf.mtext);
    if (msg_buf.mtext[len-1]=='\n');
        msg_buf.mtext[len-1]='\0';
    if (msgsnd(send_msg_id,&msg_buf,len+1,0)==-1)
        printf("\nMsg sending error\n");
}
int i=0;
while(i<9999)
    i++;
msgctl(send_msg_id,IPC_RMID,NULL);
return;
}

void *receive_message(void *a)
{
receive_key=ftok("Receiver1.c",'B');
if (receive_key==-1)
{
    printf("\nReceiver send key error");
    exit(1);
}
send_msg_id=msgget(receive_key,0777|IPC_CREAT);
if (receive_msg_id==-1)
{
    printf("\nCaller msgrcv error");
    exit(1);
}
printf("\n<<<");
while(1)
{
    if(msgrcv(receive_msg_id,&msg_buf,sizeof(msg_buf.mtext),1,0)!=-1)
        printf("<<<%s\n",msg_buf.mtext);
}
return;
 }

 void initialize()
 {
    pthread_t send_thread,receive_thread;
    pthread_create(&send_thread,NULL,send_message,NULL);
    pthread_create(&receive_thread,NULL,receive_message,NULL);
    pthread_join(send_thread,NULL);
    pthread_join(receive_thread,NULL);
    return;
 }

 int main() 
 {
    printf("\nCaller Program\n");
    initialize();
    return 0;
 }  

0 个答案:

没有答案