The Linux Programming Interface

(nextflipdebug5) #1
System V Message Queues 941

To send a message with msgsnd(), we must set the mtype field of the message structure
to a value greater than 0 (we see how this value is used when we discuss msgrcv() in
the next section) and copy the desired information into the programmer-defined mtext
field. The msgsz argument specifies the number of bytes contained in the mtext field.


When sending messages with msgsnd(), there is no concept of a partial write as
with write(). This is why a successful msgsnd() needs only to return 0, rather
than the number of bytes sent.

The final argument, msgflg, is a bit mask of flags controlling the operation of msgsnd().
Only one such flag is defined:


IPC_NOWAIT
Perform a nonblocking send. Normally, if a message queue is full, msgsnd()
blocks until enough space has become available to allow the message to be
placed on the queue. However, if this flag is specified, then msgsnd()
returns immediately with the error EAGAIN.


A msgsnd() call that is blocked because the queue is full may be interrupted by a signal
handler. In this case, msgsnd() always fails with the error EINTR. (As noted in Sec-
tion 21.5, msgsnd() is among those system calls that are never automatically restarted,
regardless of the setting of the SA_RESTART flag when the signal handler is established.)
Writing a message to a message queue requires write permission on the queue.
The program in Listing 46-2 provides a command-line interface to the msgsnd()
system call. The command-line format accepted by this program is shown in the
usageError() function. Note that this program doesn’t use the msgget() system call. (We
noted that a process doesn’t need to use a get call in order to access an IPC object in
Section 45.1.) Instead, we specify the message queue by providing its identifier as a
command-line argument. We demonstrate the use of this program in Section 46.2.2.


Listing 46-2: Using msgsnd() to send a message


––––––––––––––––––––––––––––––––––––––––––––––––––––––– svmsg/svmsg_send.c
#include <sys/types.h>
#include <sys/msg.h>
#include "tlpi_hdr.h"


#define MAX_MTEXT 1024


struct mbuf {
long mtype; / Message type /
char mtext[MAX_MTEXT]; / Message body /
};


#include <sys/types.h> /* For portability */
#include <sys/msg.h>

int msgsnd(int msqid, const void *msgp, size_t msgsz, int msgflg);
Returns 0 on success, or –1 on error
Free download pdf