Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

Section 17.2 UNIX Domain Sockets 633


#include "apue.h"
#include <sys/msg.h>
#define MAXMSZ 512
struct mymesg {
long mtype;
char mtext[MAXMSZ];
};
int
main(int argc, char *argv[])
{
key_t key;
long qid;
size_t nbytes;
struct mymesg m;
if (argc != 3) {
fprintf(stderr, "usage: sendmsg KEY message\n");
exit(1);
}
key = strtol(argv[1], NULL, 0);
if ((qid = msgget(key, 0)) < 0)
err_sys("can’t open queue key %s", argv[1]);
memset(&m, 0, sizeof(m));
strncpy(m.mtext, argv[2], MAXMSZ-1);
nbytes = strlen(m.mtext);
m.mtype = 1;
if (msgsnd(qid, &m, nbytes, 0) < 0)
err_sys("can’t send message");
exit(0);
}

Figure 17.4 Post a message to an XSI message queue

This program takes two arguments: the key associated with the queue and a string
to be sent as the body of the message. When we send messages to the server, it prints
them as shown below.
$./pollmsg & run the server in the background
[1] 12814
$queue ID 0 is 196608
queue ID 1 is 196609
queue ID 2 is 196610
$./sendmsg 0x123 "hello, world" send a message to the first queue
queue id 196608, message hello, world
$./sendmsg 0x124 "just a test" send a message to the second queue
queue id 196609, message just a test
$./sendmsg 0x125 "bye" send a message to the third queue
queue id 196610, message bye
Free download pdf