功能:消息队列的控制函数
原型
int msgctl(int msqid, int cmd, struct msqid_ds *buf);
参数
msqid: 由msgget函数返回的消息队列标识码
cmd:是将要采取的动作,(有三个可取值)
返回值:成功返回0,失败返回-1
msg_rmid.c
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#define ERR_EXIT(m) \
do \
{ \
perror(m); \
exit(EXIT_FAILURE); \
} while(0)
int main(void)
{
int msgid;
msgid = msgget(1234, 0);
if (msgid == -1)
ERR_EXIT("msgget");
printf("msgget succ\n");
printf("msgid=%d\n", msgid);
msgctl(msgid, IPC_RMID, NULL);
return 0;
}
msgset.c
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#define ERR_EXIT(m) \
do \
{ \
perror(m); \
exit(EXIT_FAILURE); \
} while(0)
int main(void)
{
int msgid;
msgid = msgget(1234, 0);
if (msgid == -1)
ERR_EXIT("msgget");
printf("msgget succ\n");
printf("msgid=%d\n", msgid);
struct msqid_ds buf;
msgctl(msgid, IPC_STAT, &buf);
sscanf("600", "%o", (unsigned int*)&buf.msg_perm.mode);
msgctl(msgid, IPC_SET, &buf);
return 0;
}
msgget.c
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#define ERR_EXIT(m) \
do \
{ \
perror(m); \
exit(EXIT_FAILURE); \
} while(0)
int main(void)
{
int msgid;
msgid = msgget(1234, 0666 | IPC_CREAT);
//msgid = msgget(1234, 0666 | IPC_CREAT | IPC_EXCL);
//msgid = msgget(IPC_PRIVATE, 0666 | IPC_CREAT | IPC_EXCL);
//msgid = msgget(IPC_PRIVATE, 0666);
//msgid = msgget(1234, 0666 | IPC_CREAT);
//msgid = msgget(1234, 0);
if (msgid == -1)
ERR_EXIT("msgget");
printf("msgget succ\n");
printf("msgid=%d\n", msgid);
return 0;
}
msgstat.c
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#define ERR_EXIT(m) \
do \
{ \
perror(m); \
exit(EXIT_FAILURE); \
} while(0)
int main(void)
{
int msgid;
msgid = msgget(1234, 0);
if (msgid == -1)
ERR_EXIT("msgget");
printf("msgget succ\n");
printf("msgid=%d\n", msgid);
struct msqid_ds buf;
msgctl(msgid, IPC_STAT, &buf);
printf("mode=%o\n", buf.msg_perm.mode);
printf("bytes=%ld\n", buf.__msg_cbytes);
printf("number=%d\n", (int)buf.msg_qnum);
printf("msgmnb=%d\n", (int)buf.msg_qbytes);
return 0;
}
makefile:
.PHONY:clean all
CC=gcc
CFLAGS=-Wall -g
BIN=msg_get msg_rmid msg_stat msg_set
all:$(BIN)
%.o:%.c
$(CC) $(CFLAGS) -c $< -o $@
clean:
rm -f *.o $(BIN)