消息队列

创建消息队列

获取消息队列ID

key_t ftok( const char * fname, int id )

msgget(0x1234,0666| IPC_CREAT);


接收消息队列

struct msgbuf{

long mtype;

char mtext[MsgHax];

};

int main(void){

key_t key;

key=ftok("./msgseedfile",'a');

printf("key =[%x]\n",key);

int msgid;

msgget(0x1234,0666);

//错误码ENOENT 消息队列不存在

if(msgid == -1){

if(errno == ENOENT){

printf("消息队列不存在");

}

perror("msgget err");

return -1;

}

struct msgbuf buf;

memset(&buf,0,sizeof(struct msgbuf));

int n;

ret = msgrcv(msgqid,&buf,MsgHax,IPC_NOWAIT);

if(ret < 0){

perror("msgsend error");

return -1;

}

buf.mtext[ret] = '\0';

printf("消息队列消息%s \n",buf.mtext);

return 0;

}


发送消息

struct msgbuf{

long mtype;

char mtext[1024];

};

int main1(void){

int msgid;

int ret=0;

msgid = msgget(0x1234,0666 | IPC_CREAT | IPC_EXECL);

if(msgid == -1){

if(errno == ENDENT){

printf("消息队列不存在\n");

}

if(errno == EEXIST){

printf("消息队列已经存在\n");

}

return -1;

}

struct msgbuf buf;

memset(&buf,0,sizeof(struct msgbuf));

buf.mtype = 1;

strcpy(buf.mtext,"11111111111dasd23dasdsa");

ret = msgsnd(msgqid,&buf,10,IPC_NOWAIT);

if(ret < 0){

perror("msgsend error");

}

return 0;

}


你可能感兴趣的