perlipcsysv-ipc

Perl: Parameters to msgsnd


I am maintaining some existing code

I see this fragment:

msgsnd( $mQueue, pack("l! a*", length($msg), $msg), 0) 
                                   || ... error handling ...

I would like to understand the call to pack() as the second argument to msgsnd.

I find the following documentation for msgsend

Calls the System V IPC function msgsnd to send the message MSG to the message queue ID. MSG must begin with the native long integer message type, be followed by the length of the actual message, and then finally the message itself. This kind of packing can be achieved with pack("l! a*", $type, $message) . Returns true if successful, false on error. See also SysV IPC in perlipc and the documentation for IPC::SysV and IPC::Msg .

This gives the second parameter to pack as $type, but does not explain what $type is. The code I'm trying to understand instead passes the message length.

What's going on? So far as I can tell the existing code is working reliably.


Solution

  • The application in question decided to use the type field to store the length of the message.

    (This is rather odd, since the size of the message is already available to the reader.)


    When the receiver request a message from the system, they may constrain the request to specific message types.

    • If msgtyp is 0, then the first message in the queue is read.

    • If msgtyp is greater than 0, then the first message in the queue of type msgtyp is read, unless MSG_EXCEPT was specified in msgflg, in which case the first message in the queue of type not equal to msgtyp will be read.

    • If msgtyp is less than 0, then the first message in the queue with the lowest type less than or equal to the absolute value of msgtyp will be read.

    If the receiver specifies 0 for msgtyp, then the message type provided by the sender isn't used by the system, and can therefore be used to carry other information.