msgctl()函数 int msgctl(int msqid, int cmd, struct msqid_ds *buf); --参数 msqid:有msgget函数返回的消息队列标识码 cmd:是将要采取的动作 --成功返回0,失败返回-1 --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 = 0; int msgid = msgget(0x1234, 0666); if (msgid == -1) { perror("msgget() err"); return -1; } printf("访问消息队列成功!msqid=%d ", msgid); struct msqid_ds buf; memset(&buf, 0, sizeof(buf)); ret = msgctl(msgid, IPC_STAT, &buf); if (ret == -1) { perror("msgctl() err"); return -1; } printf("权限位:%o ", buf.msg_perm.mode); //想要修改ipcs,需要先获取,然后再修改(这是正确的做法) buf.msg_perm.mode = 0666; ret = msgctl(msgid, IPC_SET, &buf); if (ret == -1) { perror("msgctl() err"); return -1; } printf("修改ipcs成功! "); sleep(20); ret = msgctl(msgid, IPC_RMID,NULL); if (ret == -1) { perror("msgctl() err"); return -1; } printf("删除ipcs成功! "); return 0; }