Linux 进程间通讯详解三

时间:2021-09-23 23:08:48
msgctl()函数
int msgctl(int msqid, int cmd, struct msqid_ds *buf);
--参数
msqid:有msgget函数返回的消息队列标识码
cmd:是将要采取的动作
--成功返回0,失败返回-
--cmd的三个取值
IPC_STAT--把msqid_ds结构中的数据设置为消息队列的当前关联值
IPC_SET--在进程有足够权限的前提下,把消息队列的当前关联值设置为msqid_ds数据结构中给出的值
IPC_RMID--删除消息队列
struct msqid_ds {
struct ipc_perm msg_perm; /* Ownership and permissions */
time_t msg_stime; /* Time of last msgsnd(2) */
time_t msg_rtime; /* Time of last msgrcv(2) */
time_t msg_ctime; /* Time of last change */
unsigned long __msg_cbytes; /* Current number of bytes in
queue (non-standard) */
msgqnum_t msg_qnum; /* Current number of messages
in queue */
msglen_t msg_qbytes; /* Maximum number of bytes
allowed in queue */
pid_t msg_lspid; /* PID of last msgsnd(2) */
pid_t msg_lrpid; /* PID of last msgrcv(2) */
};
struct ipc_perm {
key_t __key; /* Key supplied to msgget(2) */
uid_t uid; /* Effective UID of owner */
gid_t gid; /* Effective GID of owner */
uid_t cuid; /* Effective UID of creator */
gid_t cgid; /* Effective GID of creator */
unsigned short mode; /* Permissions */
unsigned short __seq; /* Sequence number */
};
//消息队列--msgctl()函数
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h> int main(int arg, char * args[])
{
int ret = ;
int msgid = msgget(0x1234, );
if (msgid == -)
{
perror("msgget() err");
return -;
}
printf("访问消息队列成功!msqid=%d\n", msgid);
struct msqid_ds buf;
memset(&buf, , sizeof(buf));
ret = msgctl(msgid, IPC_STAT, &buf);
if (ret == -)
{
perror("msgctl() err");
return -;
}
printf("权限位:%o\n", buf.msg_perm.mode);
//想要修改ipcs,需要先获取,然后再修改(这是正确的做法)
buf.msg_perm.mode = ;
ret = msgctl(msgid, IPC_SET, &buf);
if (ret == -)
{
perror("msgctl() err");
return -;
}
printf("修改ipcs成功!\n");
sleep();
ret = msgctl(msgid, IPC_RMID,NULL);
if (ret == -)
{
perror("msgctl() err");
return -;
}
printf("删除ipcs成功!\n");
return ;
}