Table of Contents
Model:" >Model:
Advantages of POSIX mq VS Sys V mq" >Advantages of POSIX mq VS Sys V mq
Message queue name" >Message queue name
mq_open()" >mq_open()
mq_setattr() / mq_getattr()" >mq_setattr() / mq_getattr()
mq_send() / mq_timesend()" >mq_send() / mq_timesend()
mq_receive()/mq_timedreceive()" >mq_receive()/mq_timedreceive()
mq_notify()" >mq_notify()
mq_close()" >mq_close()
mq_unlink():" >mq_unlink():
Home System Tutorial LINUX Linux IPC POSIX Message Queuing: A Simple Way to Reliable Message Delivery

Linux IPC POSIX Message Queuing: A Simple Way to Reliable Message Delivery

Feb 10, 2024 pm 02:45 PM
linux linux tutorial linux system linux command shell script 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, POSIX message queue is a relatively simple 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 methods of POSIX message queue in Linux system, including the creation, opening, sending, receiving, closing and deletion of message queue.

Linux IPC POSIX 消息队列:一种实现可靠消息传递的简单方式

Model:

#include
#include 
#include 
mq_open()   //创建/获取消息队列fd       
mq_get()    //设置/获取消息队列属性   
mq_send()/mq_receive()    //发送/接收消息 
mq_close()      //脱接消息队列            
mq_unlink()     //删除消息队列            
Copy after login

Advantages of POSIX mq VS Sys V mq

  • A simpler file-based application interface
  • Full support for message priority (priority ultimately determines the position of the message in the queue)
  • Fully supports asynchronous notification of message arrival, which is implemented through signals or thread creation
  • Timeout mechanism for blocking send and receive operations

Message queue name

Known from $man mq_overview: The message queue is uniquely identified by a name in the form of '/somename'. The maximum length of the name string cannot be towards NAME_MAX (i.e., 255), two processes Communicate by using the same message queue name

mq_open()

//创建一个POSIX消息队列或打开一个已经存在的消息队列,成功返回消息队列描述符mqdes供其他函数使用,失败返回

(mqd_t)-1设errno
//Link with -lrt.
mqd_t mq_open(const char *name, int oflag);
mqd_t mq_open(const char *name, int oflag, mode_t mode, struct mq_attr *attr);
Copy after login

oflag
must include one of:

  • O_RDONLY means opening the message queue to only receive messages
  • O_WRONLY means opening the message queue to only send messages
  • O_RDWR Indicates opening the message queue in a form that can be received and sent

can be Bitwised ORed:

  • O_NONBLOCKOpen the message queue in nonblocking mode
  • O_CREATIf a message queue does not exist, create it. The UID of the owner of the message queue is set to the effective UID of the calling process, and the GID is set to the effective GID of the calling process
  • O_EXCL Ensure that the message queue is created. If the message queue already exists, an error occurs

modeIf there is O_CREAT in oflag, then mode is used to represent the permissions of the newly created message queue
attrIf there is O_CREAT in oflag, then attr represents Attributes of the message queue. If attr is NULL, the message queue will be configured according to the default settings (mq_overview(7) for details.)

mq_setattr() / mq_getattr()

//设置/修改 / 获取消息队列属性,成功返回0,失败返回-1设errno
//Link with -lrt.
int mq_setattr(mqd_t mqdes, const struct mq_attr *newattr, struct mq_attr *oldattr);
int mq_getattr(mqd_t mqdes, struct mq_attr *attr);
Copy after login

mqattr structure

struct mq_attr {
    long mq_flags;      /* Flags: 0 or O_NONBLOCK */
    long mq_maxmsg;     /* Max. # of messages on queue */
    long mq_msgsize;    /* Max. message size (bytes) */
    long mq_curmsgs;    /* # of messages currently in queue */
};
Copy after login

mq_send() / mq_timesend()

//发送消息到mqdes指向的消息队列。成功返回0,失败返回-1设errno
//Link with -lrt.
int mq_send(mqd_t mqdes, const char *msg_ptr,size_t msg_len, unsigned int msg_prio);

//如果消息队列满
#include        //额外的header
int mq_timedsend(mqd_t mqdes, const char *msg_ptr,size_t msg_len, unsigned int msg_prio,
const struct timespec *abs_timeout);
Copy after login

msg_len msg_ptr指向的消息队列的长度,这个长度必须msg_prio 一个用于表示消息优先级的非0整数,消息按照优先级递减的顺序被放置在消息队列中,同样优先级的消息,新的消息在老的之后,如果消息队列满了,就进入blocked状态,新的消息必须等到消息队列有空间了进入,或者调用被signal中断了。如果flag里有O_NOBLOCK选项,则此时会直接报错
abs_timeout:如果消息队列满了,那么就根据abs_timeout指向的结构体表明的时间进行锁定,里面的时间是从970-01-01 00:00:00 +0000 (UTC)开始按微秒计量的时间,如果时间到了,那么mq_timesend()立即返回

struct timespec {
    time_t tv_sec;        /* seconds */
    long   tv_nsec;       /* nanoseconds */
};
Copy after login

mq_receive()/mq_timedreceive()

//从消息队列中取出优先级最高的里面的最老的消息,成功返回消息取出消息的大小,失败返回-1设errno
//具体功能参照mq_send()/mq_timesend()
//Link with -lrt.
ssize_t mq_receive(mqd_t mqdes, char *msg_ptr, size_t msg_len, unsigned int *msg_prio);
#include        //额外的header
ssize_t mq_timedreceive(mqd_t mqdes, char *msg_ptr, size_t msg_len,
 unsigned int *msg_prio, const struct timespec *abs_timeout);
Copy after login

mq_notify()

//允许调用进程注册或去注册同步来消息的通知,成功返回0,失败返回-1设errno
//Link with -lrt.
int mq_notify(mqd_t mqdes, const struct sigevent *sevp);
Copy after login

sevp指向sigevent的指针

  • 如果sevp不是NULL,那么这个函数就将调用进程注册到通知进程,只有一个进程可以被注册为通知进程
  • 如果sevp是NULL且当前进程已经被注册过了,则去注册,以便其他进程注册
union sigval {                  /* Data passed with notification */
    int     sival_int;          /* Integer value */
    void*   sival_ptr;          /* Pointer value */
};
struct sigevent {
    int     sigev_notify;       /* Notification method */
    int     sigev_signo;        /* Notification signal */
    union sigval    sigev_value;    /* Data passed with notification */
    void(*sigev_notify_function) (union sigval); //Function used for thread notification
 (SIGEV_THREAD)
    void*   sigev_notify_attributes;    // Attributes for notification thread (SIGEV_THREAD)
    pid_t   sigev_notify_thread_id;     /* ID of thread to signal (SIGEV_THREAD_ID) */
};
Copy after login

sigev_notify使用下列的宏进行配置:

  • SIGEV_NONE调用进程仍旧被注册,但是有消息来的时候什么都不通知
  • SIGEV_SIGNAL通过给调用进程发送sigev_signo指定的信号来通知进程有消息来了
  • SIGEV_THREAD一旦有消息到了,就激活sigev_notify_function作为新的线程的启动函数

mq_close()

//关闭消息队列描述符mqdes,如果有进程存在针对这个队列的notification request,那么也会被移除

//成功返回0,失败返回-1设errno
//Link with -lrt.
int mq_close(mqd_t mqdes);
Copy after login
//移除队列名指定的消息队列,一旦最后一个进程关闭了针对这个消息队列的描述符,就会销毁这个消息队列
//成功返回0,失败返回-1设errno
//Link with -lrt.
int mq_unlink(const char *name);
Copy after login

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

The above is the detailed content of Linux IPC POSIX Message Queuing: A Simple 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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Android TV Box gets unofficial Ubuntu 24.04 upgrade Android TV Box gets unofficial Ubuntu 24.04 upgrade Sep 05, 2024 am 06:33 AM

For many users, hacking an Android TV box sounds daunting. However, developer Murray R. Van Luyn faced the challenge of looking for suitable alternatives to the Raspberry Pi during the Broadcom chip shortage. His collaborative efforts with the Armbia

deepseek web version entrance deepseek official website entrance deepseek web version entrance deepseek official website entrance Feb 19, 2025 pm 04:54 PM

DeepSeek is a powerful intelligent search and analysis tool that provides two access methods: web version and official website. The web version is convenient and efficient, and can be used without installation; the official website provides comprehensive product information, download resources and support services. Whether individuals or corporate users, they can easily obtain and analyze massive data through DeepSeek to improve work efficiency, assist decision-making and promote innovation.

How to install deepseek How to install deepseek Feb 19, 2025 pm 05:48 PM

There are many ways to install DeepSeek, including: compile from source (for experienced developers) using precompiled packages (for Windows users) using Docker containers (for most convenient, no need to worry about compatibility) No matter which method you choose, Please read the official documents carefully and prepare them fully to avoid unnecessary trouble.

BitPie Bitpie wallet app download address BitPie Bitpie wallet app download address Sep 10, 2024 pm 12:10 PM

How to download BitPie Bitpie Wallet App? The steps are as follows: Search for "BitPie Bitpie Wallet" in the AppStore (Apple devices) or Google Play Store (Android devices). Click the "Get" or "Install" button to download the app. For the computer version, visit the official BitPie wallet website and download the corresponding software package.

BITGet official website installation (2025 beginner's guide) BITGet official website installation (2025 beginner's guide) Feb 21, 2025 pm 08:42 PM

BITGet is a cryptocurrency exchange that provides a variety of trading services including spot trading, contract trading and derivatives. Founded in 2018, the exchange is headquartered in Singapore and is committed to providing users with a safe and reliable trading platform. BITGet offers a variety of trading pairs, including BTC/USDT, ETH/USDT and XRP/USDT. Additionally, the exchange has a reputation for security and liquidity and offers a variety of features such as premium order types, leveraged trading and 24/7 customer support.

Detailed explanation: Shell script variable judgment parameter command Detailed explanation: Shell script variable judgment parameter command Sep 02, 2024 pm 03:25 PM

The system variable $n is the parameter passed to the script or function. n is a number indicating the number of parameters. For example, the first parameter is $1, and the second parameter is $2$? The exit status of the previous command, or the return value of the function. Returns 0 on success, 1 on failure $#Number of parameters passed to the script or function $* All these parameters are enclosed in double quotes. If a script receives two parameters, $* is equal to $1$2$0The name of the command being executed. For shell scripts, this is the path to the activated command. When $@ is enclosed in double quotes (""), it is slightly different from $*. If a script receives two parameters, $@ is equivalent to $1$2$$the process number of the current shell. For a shell script, this is the process I when it is executing

Zabbix 3.4 Source code compilation installation Zabbix 3.4 Source code compilation installation Sep 04, 2024 am 07:32 AM

1. Installation environment (Hyper-V virtual machine): $hostnamectlStatichostname:localhost.localdomainIconname:computer-vmChassis:vmMachineID:renwoles1d8743989a40cb81db696400BootID:renwoles272f4aa59935dcdd0d456501Virtualization:microsoftOperatingSystem:CentOS Linux7(Core)CPEOSName:cpe:

Ouyi okx installation package is directly included Ouyi okx installation package is directly included Feb 21, 2025 pm 08:00 PM

Ouyi OKX, the world's leading digital asset exchange, has now launched an official installation package to provide a safe and convenient trading experience. The OKX installation package of Ouyi does not need to be accessed through a browser. It can directly install independent applications on the device, creating a stable and efficient trading platform for users. The installation process is simple and easy to understand. Users only need to download the latest version of the installation package and follow the prompts to complete the installation step by step.

See all articles