linux 進程間通信系列6,使用消息隊列(message queue)
概念:消息排隊,先進先出(FIFO),消息一旦出隊,就從隊列里消失了。
1,創建消息隊列(message queue)
2,寫消息到消息隊列(message queue)
3,從消息隊列(message queue)讀消息
3,刪除消息隊列(message queue)
1,創建消息隊列(message queue)
#include <stdio.h>
#include <string.h>
#include <sys/ipc.h>
#include <sys/msg.h>
int main(){
int msgid;
msgid = msgget(IPC_PRIVATE, 0600);
if(msgid < 0){
perror("msgget");
return 1;
}
printf("%d\n", msgid);
return 0;
}
用下面的命令,能夠查看到上面的程序創建的共享內存。
ipcs -q
執行后的結果:
------ Message Queues --------
key msqid owner perms used-bytes messages
0x00000000 32768 ys 600 0 0
2,寫消息到消息隊列(message queue)
#include <stdio.h>
#include <string.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdlib.h>
#define MTEXTSIZE 10
int main(int argc, char* argv[]){
int msgid;
struct msgbuf{
long mtype;
char mtext[MTEXTSIZE];
}mbuf;
if(argc != 2){
printf("wrong argc");
return 1;
}
msgid = atoi(argv[1]);
mbuf.mtype = 777;
memset(mbuf.mtext, 0, sizeof(mbuf.mtext));
mbuf.mtext[0] = 'A';
if(msgsnd(msgid, &mbuf, MTEXTSIZE, 0) != 0){
perror("msgsnd");
return 1;
}
return 0;
}
執行方法:【ipcs -q】執行后,得到下面的數字。
./a.out 789884
執行后:ipcs -q 發現, message下面的數字從0變為1了,說明消息隊列里有了一個消息。
------ Message Queues --------
key msqid owner perms used-bytes messages
0x00000000 32768 ys 600 10 1
3,從消息隊列(message queue)讀消息
#include <stdio.h>
#include <string.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdlib.h>
#define MTEXTSIZE 10
int main(int argc, char* argv[]){
int msgid, msgtype;
struct msgbuf{
long mtype;
char mtext[MTEXTSIZE];
}mbuf;
if(argc != 3){
printf("wrong argc");
return 1;
}
msgid = atoi(argv[1]);
msgtype = atoi(argv[2]);
if(msgrcv(msgid, &mbuf, MTEXTSIZE, msgtype, 0) <= 0){
perror("msgrcv");
return 1;
}
printf("%c\n", mbuf.mtext[0]);
return 0;
}
執行方法:必須指定在寫入消息是的type,也就是777
./a.out 32768 777
執行后,ipcs -q發現,message下面的數字,由1變為0了,說明消息隊列里沒有消息了。
------ Message Queues --------
key msqid owner perms used-bytes messages
0x00000000 32768 ys 600 0 0
4,刪除消息隊列(message queue)
#include <stdio.h>
#include <string.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdlib.h>
int main(int argc, char* argv[]){
int msgid;
msqid_ds mds;
if(argc != 2){
printf("wrong argv\n");
return 1;
}
msgid = atoi(argv[1]);
if(msgctl(msgid, IPC_RMID, &mds) != 0){
perror("msgctl");
return 1;
}
return 0;
}
執行方法:
./a.out 32768
執行后,ipcs -q發現,消息隊列本身都沒有了。
------ Message Queues --------
key msqid owner perms used-bytes messages
用命令行刪除共享內存:【ipcs -q】執行后,得到下面的數字。
ipcrm -q id