编程接口指南

发送和接收消息

msgsnd(2)msgrcv(2) 分别发送和接收消息。 msqid 参数必须为现有消息队列的 ID。 msgp 参数是指向包含消息类型及其文本的结构的指针。 msgsz 参数以字节为单位指定消息的长度。 msgflg 参数传递各种控制标志。

以下代码说明了 msgsnd(2)msgrcv(2)

#include <sys/types.h>

 #include <sys/ipc.h>

 #include <sys/msg.h>



 ...

 	int				msgflg;	/* message flags for the operation */

 	struct msgbuf 	*msgp;	/* pointer to the message buffer */

 	size_t			msgsz;	/* message size */

		size_t			maxmsgsize;

 	long				msgtyp;	/* desired message type */

 	int				msqid		/* message queue ID to be used */

 	...

 	msgp = malloc(sizeof(struct msgbuf) – sizeof (msgp–>mtext) 

							+ maxmsgsz);

 	if (msgp == NULL) {

 		(void) fprintf(stderr, "msgop: %s %ld byte messages.\n",

 				"could not allocate message buffer for", maxmsgsz);

 		exit(1);

 		...

 		msgsz = ...

 		msgflg = ...

 		if (msgsnd(msqid, msgp, msgsz, msgflg) == –1)

 			perror("msgop: msgsnd failed");

 		...

 		msgsz = ...

 		msgtyp = first_on_queue;

 		msgflg = ...

 		if (rtrn = msgrcv(msqid, msgp, msgsz, msgtyp, msgflg) == –1)

 			perror("msgop: msgrcv failed");

 		...