消息隊列ui
1.頭文件spa
#pragma once #include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct msgbuf{ long mtype; char mtext[20]; }msgbuf;
2.servercode
#include"msg.h" int main(void) { key_t key = ftok("/", 0x1111); // 獲取惟一鍵值 if(key<0){ perror("ftok failed"); exit(1); } int msgid = msgget(key,0666|IPC_CREAT); // 獲取消息隊列標識符 if(msgid<0){ perror("msgget failed"); exit(1); } msgbuf *buf = NULL; buf = (msgbuf*)malloc(sizeof(msgbuf)); // 寫 if(buf==NULL){ perror("malloc"); exit(1); } buf->mtype = 10; while(1){ fgets(buf->mtext,20,stdin); msgsnd(msgid,buf,sizeof(((msgbuf*)0)->mtext),0); printf("send success %s",buf->mtext); if(strncmp("quit",buf->mtext,4)==0) break; } msgctl(msgid,IPC_RMID,NULL); // 刪除 return 0; }
3.clientserver
#include "msg.h" int main(void) { key_t key = ftok("/",0x1111); // 獲取惟一鍵值 if(key<0){ perror("ftok failed"); exit(1); } int msgid = msgget(key,0666); //建立消息隊列標識符 if(msgid<0){ perror("msgget failed"); exit(1); } msgbuf buf; // 讀 while(1){ int a = msgrcv(msgid, &buf, sizeof(((msgbuf*)0)->mtext),0,0); if(a=0) printf("not rcv"); if(strncmp("quit",buf.mtext,4)==0) break; printf("%s",buf.mtext); } msgctl(msgid,IPC_RMID,NULL); // 刪除 return 0 ; }
success !blog