#include<sys/types.h>
#include<sys/msg.h>
#include<sys/ipc.h>
#include<unistd.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<errno.h>
#define ADDRESS "/home/train/xq/xiaoxi"
#define size 1024
struct msgbuf{
long mytype;
char data[size];
}
int main(){
key_t key;
int msgid;
struct msgbuf msg_buf;
int running=1;
key=ftok("ADDRESS",'A');
printf("key is %x\n",key);
msgid=msgget(key,IPC_CREAT|0666);
if(msgid==-1){
printf("creat error\n");
exit(1);
}
while(running){
char buffer[BUFSIZ];
int send;
msg_buf.mytype=1;
printf("Pleasa enter some message.....\n");
fgets(buffer,BUFSIZ,stdin);
strcpy(msg_buf.data,buffer);
send=msgsnd(msgid,&msg_buf,size,IPC_NOWAIT);
if (send==-1){
printf("msgsend is failed\n");
exit (1);
}
if (strncmp(buffer,"end",3)==0){
running=0;
}
}
exit(0);
}
为什么报错?msg_read.c:17: error: two or more data types in declaration specifiers
struct msgbuf{
long mytype;
char data[size];
};
结构体定义结束请加上分号
因为你没有设置等待msgsnd发送信息的时间,程序运行是很快的,你在上一个程序发送一条信息,这边接收到了信息,又接着读信息。但此时你还没有发送消息,导致读不到消息,msgrcv返回-1退出程序。可以在前面加一个sleep语句等待发送信息。