简体   繁体   English

如何处理大小不同的Linux消息队列(POSIX或SysV)中的信号?

[英]How to handle signals in Linux Message Queues (POSIX or SysV) with different sizes?

What is the best way to handle signals for a Linux Message Queue (POSIX or SysV) with signals that have different sizes? 处理具有不同大小的信号的Linux消息队列(POSIX或SysV)的信号的最佳方法是什么?

Suppose I have a process which could receive two or more different signals with different sizes. 假设我有一个过程可以接收两个或更多个大小不同的信号。 For example: 例如:

struct sig1 {
   long mType;
   char data[10];
};

struct sig2 {
   long mType;
   char data[20000];
};

Now, as I understand the message queue API, in order to receive these signals I need to make sure that I can provide a buffer for the data which is at least equal to the size of the largest message passed in the message queue. 现在,据我所知,消息队列API为了接收这些信号,我需要确保可以为数据提供一个缓冲区,该缓冲区至少等于在消息队列中传递的最大消息的大小。

int msgrcv(int msqid, void *msgp, size_t msgsz,
           long msgtyp, int msgflg);

To me it seems impractical that I need to allocte a new buffer for every signal that I receive that is as large as the largest message passed in the queue. 对我来说,为收到的每个信号分配与队列中传递的最大消息一样大的信号,这似乎是不切实际的。 Or is there any way to poll the queue to know how large the message is before taking it out from the queue? 还是有什么方法可以在从队列中取出消息之前轮询队列以了解消息的大小? Now in the extreme case I provided above I would need to allocate 20000 bytes for every signal received even though when the sig1 is received, only 10 bytes would suffice. 现在,在我上面提供的极端情况下,即使接收到sig1时,我也需要为接收到的每个信号分配20000字节,但仅10个字节就足够了。

Suppose I have an application with high signaling load and signals with large different in sizes. 假设我有一个具有高信令负载和大小差异很大的信号的应用程序。 Is there a good way to handle this case? 是否有处理此案的好方法? Also, in a performance perspective, will I lose performance since I need to allocate larger buffers for every receive? 此外,从性能角度来看,由于我需要为每次接收分配更大的缓冲区,我是否会失去性能?

Sorry, complete rewrite, I confused the msgrcv with reading from pipes and sockets, where each packet can be read in part or as a whole. 抱歉,完全重写了,我将msgrcv与从管道和套接字读取的信息混淆了,在这里可以部分或整体读取每个数据包。

You need to have a receiving buffer that is large enough for the largest message of all that you may receive. 您需要具有足够大的接收缓冲区,以容纳所有可能收到的最大消息。

The actual size is returned as the return value from msgrcv , so something like this: 实际大小作为msgrcv的返回值返回,所以像这样:

 struct sig2 msg;
 size_t n = msgrcv(queue_id, &msg, sizeof(msg.data), -1, 0);
 if (n == -1)
 {
    ... error - inspect errno to understand what went wrong ... 
 }

Note also that the default size is 16384 bytes, so a 20000 byte array may not work unless you reconfigure the default message size. 另请注意,默认大小为16384字节,因此,除非您重新配置默认消息大小,否则20000字节数组可能不起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM