1.msgctl函数
msgctl函数可以对消息队列进行各种控制,如修改消息队列的属性,或删除消息消息队列。
#include <sys/msg.h>
int msgctl(int msqid, int cmd, struct msqid_ds *buf);
参数:
返回值: 成功:0 失败:-1
2.实例
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>
#define N 128
typedef struct _msg
{
long mtype; // 消息类型
char mtext[N]; // 消息正文
//... // 消息的正文可以有多个成员
}MSG;
//定义消息体长度
#define MSG_SIZE (sizeof(MSG)-sizeof(long))
int main(int argc, char *argv[])
{
key_t key;
int msgqid;
key = ftok(".", 2021); // key 值
if (key == -1)
{
perror("error to ftok:");
exit(1);
}
// 创建消息队列
msgqid = msgget(key, IPC_CREAT | 0666);
if (msgqid == -1)
{
perror("error to create message queue:");
exit(1);
}
printf("key=%#x\n",key);
printf("msgqid=%d\n",msgqid);
system("ipcs -q");
//删除消息队列
if(msgctl(msgqid,IPC_RMID,NULL)==-1){
perror("error to remove msg queue:");
exit(1);
}
system("ipcs -q");
return 0;
}
运行结果:
[root@iz2zefozq9h39txdb8s7npz shelldemo]# ./a.out
key=0xe5010131
msgqid=131072
------ Message Queues --------
key msqid owner perms used-bytes messages
0xe5010131 131072 root 666 256 2
------ Message Queues --------
key msqid owner perms used-bytes messages