• Linux ipc通信(消息对列)


    前言:消息队列也是linux开发ipc机制中较为重要的一个进程间通信机制。

    1.系统创建或获取消息对列
    int msgget(key_t key, int mode);

    创建消息队列,或者获取消息队列。
    参数:
    key - 使用ftok()获取到的key
    mode - IPC_CREAT|0666
    返回:
    消息队列的ID

    2.往队列里发送一条消息。此操作被中断后不会被重启(信号处理中SA_RESTART)

    int msgsnd(int msqid, const void *msgp, size_t msgsz, int msgflg);

    参数:
    msgid: - 消息队列的id
    msgp - 消息,通常为下面的结构体
    struct msgbuf{
    long mtype; /消息类型,必需>0/
    char mtext[100]; /消息数据,可自定义类型与大小/
    };
    msgsz - 消息的长度,指的消息数据的长度
    msgflg - IPC_NOWAIT(不阻塞),MSG_EXCEPT(接受不检测mtype),MSG_NOERROR(消息数据过长时会截断数据)
    返回:
    0表示成功, -1表示失败

    *3.int msgrcv(int msgid, void msgp, int msgsz, long msgtyp, int msgflg);

    作用:接收消息队列中的消息

    所需要的头文件:
    #include
    #include
    #include

    在这里插入图片描述
    *4.int msgctl(int msqid, int cmd, struct msqid_ds buf)

    作用:msgctl系统调用对msqid标识的消息队列执行cmd命令操作。

    返回值:0,成功;-1,失败;EFAULT(buf指向的地址无效);EIDRM(在读取中队列被删除);EINVAL(msgqid无效,或者msgsz小于0);EPERM(IPC_SET或者IPC_RMID命令被使用,但调用程序没有写的权限)

    使用命令:
    IPC_STAT:读取消息队列的数据结构msqid_ds,并将其存储在buf指定的地址中。

    IPC_SET:设置消息队列的数据结构msqid_ds中的ipc_perm元素的值。这个值取自buf参数。

    IPC_RMID:从系统内核中移走消息队列。

    我们再说一下队列的msqid_ds结构体,对于每一个队列都有一个msqid_ds来描述队列当前的状态
    struct msqid_ds {//Linux系统中的定义
    struct ipc_perm msg_perm; /* Ownership and permissions
    time_t msg_stime; /* Time of last msgsnd() /
    time_t msg_rtime; /
    Time of last msgrcv() /
    time_t msg_ctime; /
    Time of last change /
    unsigned long __msg_cbytes; /
    Current number of bytes inqueue (non-standard) /
    msgqnum_t msg_qnum; /
    Current number of messagesin queue /
    msglen_t msg_qbytes; /
    Maximum number of bytesallowed in queue /
    pid_t msg_lspid; /
    PID of last msgsnd() /
    pid_t msg_lrpid; /
    PID of last msgrcv() */
    };//不同的系统中此结构会有不同的新成员。这个结构体的作用是用来管理消息队列的,通过cmd指令来设置这结构体中的值,进而达到控制消息队列的目的

  • 相关阅读:
    在 EF Core 7 中实现强类型 ID
    如何搭建双 M 结构的主从备份?
    vue实现响应式改变scss样式
    LINUX漏洞复现篇之ShellShock漏洞
    CAN测量模块总线负载率,你关注了吗?
    F - New Year Snowmen
    【Python数据分析】Pandas常用操作(二)
    夏日里的清凉
    Alibaba Druid整合
    电脑不在身边能远程控制吗?
  • 原文地址:https://blog.csdn.net/slgcsdn/article/details/132793132