Table of Contents
Model" >Model
ftok()" >ftok()
msgget()" >msgget()
msgsnd()" >msgsnd()
msgrcv()" >msgrcv()
msgctl()" >msgctl()
例子" >例子
Home System Tutorial LINUX Linux IPC System V Message Queuing: A Classic Way to Reliable Message Delivery

Linux IPC System V Message Queuing: A Classic Way to Reliable Message Delivery

Feb 12, 2024 pm 03:33 PM
linux linux tutorial linux system linux command shell script typedef lsp embeddedlinux Getting started with linux linux learning

Linux system is an operating system that supports concurrent execution of multi-tasks. It can run multiple processes at the same time, thereby improving system utilization and efficiency. However, if data exchange and collaboration are required between these processes, some inter-process communication (IPC) methods need to be used, such as signals, shared memory, semaphores, etc. Among them, System V message queue is a relatively classic and reliable IPC method. It allows two or more processes to transmit messages through a queue without caring about the content and format of the message. This article will introduce the method of System V message queue in Linux system, including the creation, opening, sending, receiving, closing and deletion of message queue.

Linux IPC System V 消息队列:一种实现可靠消息传递的经典方式

Model

#include 
#include 
#include 
ftok()               //获取key值                               
msgget()             //创建/获取消息队列                        
msgsnd()/msgrcv()    //发消息到消息队列/从消息队列收信息        
msgctl()             //删除消息队列                           
Copy after login

ftok()

//获取key值, key值是System V IPC的标识符,成功返回key,失败返回-1设errno
//同pathname+同 proj_id==>同key_t;
key_t ftok(const char *pathname, int proj_id);
Copy after login

pathname: File name
proj_id: a number from 1 to 255, representing project_id

key_t key=ftok(".",100);    //“.”就是一个存在且可访问的路径, 100是假设的proj_id
    if(-1==key)
        perror("ftok"),exit(-1);
Copy after login

msgget()

//创建/获取消息队列,成功返回shmid,失败返回-1
int msgget(key_t key, int msgflg);  //ATTENTION:用int msqid=msgget()比较好看
Copy after login

msgflg: Specific operation flag

  • IPC_CREAT If it does not exist, create it. You need to set "|Permission Information" in msgflg; if it exists, open it
  • IPC_EXCLIf it exists, the creation fails
  • 0 Get the existing message queue

The capacity of the message queue is controlled by msg_qbytes. During the process of creating the message queue, this size is initialized to MSGMNB. This limit can be modified through msgctl()

int msqid=msgget(key,IPC_CREAT|IPC_EXCL|0664);
if(-1==msqid)
    perror("msgget"),exit(-1);
Copy after login

msgsnd()

//向指定的消息队列发送指定的消息,如果消息队列已经满了,默认的行为是堵塞,直到队列有空间容纳新的消息,成

功返回0,失败返回-1设errno
int msgsnd(int msqid, const void *msgp, size_t msgsz, int msgflg);
Copy after login

msqid The ID of the message queue returned by msgget()
msgpThe first address of the message, the reference data type of the message is as follows

struct msgbuf {
    long mtype;       /* message type, must be > 0 */   //消息的类型
    char mtext[1];    /* message data */                //消息的内容
};
ATTENTION:The  mtext field is an array (or other structure) whose size is
 specified by msgsz, a nonnegative integer value. 
Copy after login

msgszThe size of the message. This parameter is used to specify the size of the message content, excluding the type of the message. Only sizeof(Msgbuf.mtext), not sizeof(Msgbuf)
msgflgThe flag sent, default to 0

Msg msg1={1,"hello"};//消息的类型是1,内容是hello
int res=msgsnd(msqid,&msg2,sizeof(msg2.buf),0);
if(-1==res)
    perror("msgsnd"),exit(-1);
Copy after login

msgrcv()

//向指定的消息队列取出指定的消息,成功返回实际接受到的byte数,失败返回-1设errno
ssize_t msgrcv(int msqid, void *msgp, size_t msgsz, long msgtyp, int msgflg);
Copy after login

msqid: The ID of the message queue (returned by msgget)
msgp: The first address of the buffer where the received message is stored
msgsz : The maximum size of the message, excluding the type of the message ==>Only sizeof(Msgbuf.mtext), not sizeof(Msgbuf)

  • If the length of the message is >msgsz and there is MSG_NOERROR in msgflg, the message will be truncated and the truncated part will be lost
  • If the length of the message is > msgsz and there is no MSG_NOERROR in msgflg, an error will occur and E2BIG will be reported.

msgtyp: Message type

  • 0:Read the first message in the message queue
  • >0: Read the first message of type msgtype in the message queue, unless there is MSG_EXCEPT in msg_flg, then the first message in the queue that is not msgtyp will be read
  • Read type
  • in the message queue

msgflg: Flag to send, default to 0

Msg msg1;
int res=msgrcv(msqid,&msg1,sizeof(msg1.buf),1,0);
if(-1==res)
    perror("msgrcv"),exit(-1);
Copy after login

msgctl()

// 消息操作,成功返回0,失败返回-1设errno
int msgctl(int msqid, int cmd, struct msqid_ds *buf);
Copy after login

msqid :消息队列的ID,由msgget()
buf 结构体指针

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 (nonstandard) */
    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 */
};
Copy after login

cmd

  • IPC_STAT从内核相关结构体中拷贝消息队列相关的信息到buf指向的结构体中

  • IPC_SET把buf指向的结构体的内容写入到内核相关的结构体中,同时更显msg_ctimer成员,同时以下成员也会被更新:msg_qbytes, msg_perm.uid, msg_perm.gid, msg_perm.mode。调用队列的进程的effective UID必须匹配队列所有者或创建者的msg_perm.uid或msg_perm.cuid或者该进程拥有特权级别,

  • IPC_RMID立即销毁消息队列,唤醒所有正在等待读取或写入该消息队列进程,调用的进程的UID必须匹配队列所有者或创建者或者该进程拥有足够的特权级别

  • IPC_INFO (Linux-specific)返回整个系统对与消息队列的限制信息到buf指向的结构体中

    //_GNU_SOURCE
    //
    struct msginfo {
        int msgpool;/*Size in kibibytes of buffer pool used to hold message
     data; unused within kernel*/
        int msgmap; /*Maximum number of entries in message map; unused within 
    kernel*/
        int msgmax; /*Maximum number of bytes that can be written in a single
     message*/
        int msgmnb; /*Maximum number of bytes that can be written to queue; 
    used to initialize msg_qbytes  during queue creation*/
        int msgmni; /*Maximum number of message queues*/
        int msgssz; /*Message segment size; unused within kernel*/
        int msgtql; /*Maximum number of messages on all queues in system; unused
     within kernel*/
        unsigned short int  msgseg; /*Maximum number of segments; unused
     within kernel*/
    };
    
    Copy after login
    int res=msgctl(msqid,IPC_RMID,NULL);
    if(-1==res)
    perror("msgctl"),exit(-1);
    
    Copy after login

例子

//Sys V IPC msg
#include
#include
#include
#include
#include
typedef struct{
    long mtype;     //消息的类型
    char buf[20];       //消息的内容
}Msg;
int msqid;          //使用全局变量,这样就可以在fa中使用msqid了
void fa(int signo){
    printf("deleting..\n");
    sleep(3);
    int res=msgctl(msqid,IPC_RMID,NULL);
    if(-1==res)
        perror("msgctl"),exit(-1);
    exit(0);
}
int main(){
    //ftok()
    key_t key=ftok(".",150);
    if(-1==key)
        perror("ftok"),exit(-1);
    printf("key%#x\n",key);
    //msgget()
    msqid=msgget(key,IPC_CREAT|IPC_EXCL|0664);
    if(-1==msqid)
        perror("msgget"),exit(-1);
    printf("msqid%d\n",msqid);
    //msgsnd()
    Msg msg1={1,"hello"};//消息的类型是1,内容是hello
    Msg msg2={2,"world"};
    int res=msgsnd(msqid,&msg2,sizeof(msg2.buf),0);
    if(-1==res)
        perror("msgsnd"),exit(-1);
    res=msgsnd(msqid,&msg1,sizeof(msg1.buf),0);
    if(-1==res)
        perror("msgsnd"),exit(-1);
    //msgctl()
    //Ctrl+C delete msq
    printf("Press CTRL+C to delete msq\n");
    if(SIG_ERR==signal(SIGINT,fa))
        perror("signal"),exit(-1);
    while(1);
    return 0;
}
Copy after login

本文介绍了Linux系统中System V 消息队列的方法,包括消息队列的创建、打开、发送、接收、关闭和删除等方面。通过了解和掌握这些知识,我们可以更好地使用System V 消息队列来实现进程间通信,提高系统的稳定性和效率。当然,Linux系统中System V 消息队列还有很多其他的特性和用法,需要我们不断地学习和研究。希望本文能给你带来一些启发和帮助。

The above is the detailed content of Linux IPC System V Message Queuing: A Classic Way to Reliable Message Delivery. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What computer configuration is required for vscode What computer configuration is required for vscode Apr 15, 2025 pm 09:48 PM

VS Code system requirements: Operating system: Windows 10 and above, macOS 10.12 and above, Linux distribution processor: minimum 1.6 GHz, recommended 2.0 GHz and above memory: minimum 512 MB, recommended 4 GB and above storage space: minimum 250 MB, recommended 1 GB and above other requirements: stable network connection, Xorg/Wayland (Linux)

vscode cannot install extension vscode cannot install extension Apr 15, 2025 pm 07:18 PM

The reasons for the installation of VS Code extensions may be: network instability, insufficient permissions, system compatibility issues, VS Code version is too old, antivirus software or firewall interference. By checking network connections, permissions, log files, updating VS Code, disabling security software, and restarting VS Code or computers, you can gradually troubleshoot and resolve issues.

How to run java code in notepad How to run java code in notepad Apr 16, 2025 pm 07:39 PM

Although Notepad cannot run Java code directly, it can be achieved by using other tools: using the command line compiler (javac) to generate a bytecode file (filename.class). Use the Java interpreter (java) to interpret bytecode, execute the code, and output the result.

What is vscode What is vscode for? What is vscode What is vscode for? Apr 15, 2025 pm 06:45 PM

VS Code is the full name Visual Studio Code, which is a free and open source cross-platform code editor and development environment developed by Microsoft. It supports a wide range of programming languages ​​and provides syntax highlighting, code automatic completion, code snippets and smart prompts to improve development efficiency. Through a rich extension ecosystem, users can add extensions to specific needs and languages, such as debuggers, code formatting tools, and Git integrations. VS Code also includes an intuitive debugger that helps quickly find and resolve bugs in your code.

Can vscode be used for mac Can vscode be used for mac Apr 15, 2025 pm 07:36 PM

VS Code is available on Mac. It has powerful extensions, Git integration, terminal and debugger, and also offers a wealth of setup options. However, for particularly large projects or highly professional development, VS Code may have performance or functional limitations.

How to use VSCode How to use VSCode Apr 15, 2025 pm 11:21 PM

Visual Studio Code (VSCode) is a cross-platform, open source and free code editor developed by Microsoft. It is known for its lightweight, scalability and support for a wide range of programming languages. To install VSCode, please visit the official website to download and run the installer. When using VSCode, you can create new projects, edit code, debug code, navigate projects, expand VSCode, and manage settings. VSCode is available for Windows, macOS, and Linux, supports multiple programming languages ​​and provides various extensions through Marketplace. Its advantages include lightweight, scalability, extensive language support, rich features and version

What is the main purpose of Linux? What is the main purpose of Linux? Apr 16, 2025 am 12:19 AM

The main uses of Linux include: 1. Server operating system, 2. Embedded system, 3. Desktop operating system, 4. Development and testing environment. Linux excels in these areas, providing stability, security and efficient development tools.

How to check the warehouse address of git How to check the warehouse address of git Apr 17, 2025 pm 01:54 PM

To view the Git repository address, perform the following steps: 1. Open the command line and navigate to the repository directory; 2. Run the "git remote -v" command; 3. View the repository name in the output and its corresponding address.

See all articles