我需要发送一条不确定大小的消息,以便第二个程序显示接收到的消息的大小,为其分配内存,接收并打印它
我的第一个程序一直等到用户输入一条消息,为其分配内存,然后将消息的大小发送给另一个程序,然后再发送消息本身。
我的第二个程序接收到一条消息,该消息具有将要到达的消息大小,但是同时它没有收到消息本身,并且我不知道如何解决此问题
程序1。发件人
#include <stdio.h>
#include <string.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <sys/types.h>
#include <stdlib.h>
struct msgbuf
{
long type;
char mtext[1];
};
struct size
{
long type;
char sz[1];
};
void send_message(int mqid)
{
char mes[1000];
struct msgbuf *buffer;
struct size buf;
buf.type = 1;
int length;
//memset(buffer.mtext,sizeof(buffer.mtext));
for(int i = 0; i < 4;i++){
fgets(mes,sizeof(mes),stdin);
sprintf(buf.sz,"%ld",strlen(mes));
length = strlen(mes)+1;
if(msgsnd(mqid,&buf,sizeof(buf.sz),0)<0)
perror("msgsnd");
printf("Size: %d\n",strlen(mes));
buffer = malloc(sizeof(struct msgbuf)-1 + length);
buffer->type = 2;
strncpy(buffer->mtext,mes,strlen(mes));
if(msgsnd(mqid,&buffer,length,0)<0)
perror("msgsnd");
else
printf("Send message: %s\n",buffer->mtext);
//free(buffer);
}
}
int main()
{
int key = ftok("comm",8);
if(key < 0)
perror("ftok");
int id = msgget(key,0600);
if(id < 0)
perror("msgget");
send_message(id);
return 0;
}
程序2
#include <stdio.h>
#include <string.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <sys/types.h>
#include <stdlib.h>
struct msgbuf
{
long type;
char mtext[1];
};
struct size
{
long type;
char sz[1];
};
void receive_message(int mqid)
{
struct msgbuf *buffer;
struct size szbuf;
int a;
for(int i = 0; i < 4;i++){
if(msgrcv(mqid,&szbuf,sizeof(szbuf.sz),1,0)<0)
perror("msgrcv");
else
printf("Size: %s\n",szbuf.sz);
printf("Hello\n");
a = atoi(szbuf.sz);
printf("%d\n",a);
/*szbuf = (struct size*) malloc(sizeof(struct size) - 1 + a);
if(msgrcv(mqid,szbuf,sizeof(szbuf->sz),2,0)<0)
perror("msgrcv");
else
printf("Size: %s\n",szbuf->sz);*/
struct msgbuf* buffer = (struct msgbuf*)malloc(sizeof(struct msgbuf)-1 + a);
if(msgrcv(mqid,buffer,sizeof(buffer->mtext),0)<0)
perror("msgrcv");
else
printf("Received message: %s\n",buffer->mtext);
free(buffer);
}
}
int main()
{
int key = ftok("comm",8);
if(key < 0)
perror("ftok");
int id = msgget(key,0600|IPC_CREAT|IPC_EXCL);
if(id < 0)
perror("msgget");
receive_message(id);
if(msgctl(id,IPC_RMID,0)<0)
perror("msgctl");
return 0;
}
收件人程序应打印传入邮件的大小和邮件本身