清单 2 显示了消息队列的消息提交部分。
清单 2. 向消息队列提交消息的程序
#include <sys/types.h>
#include <sys/msg.h>
#include <sys/ipc.h>
#include <string.h>
#include <stdio.h>
int main (void) {
key_t ipckey;
int mq_id;
struct { long type; char text[100]; } mymsg;
/* Generate the ipc key */
ipckey = ftok("/tmp/foo", 42);
printf("My key is %dn", ipckey);
/* Set up the message queue */
mq_id = msgget(ipckey, IPC_CREAT | 0666);
printf("Message identifIEr is %dn", mq_id);
/* Send a message */
memset(mymsg.text, 0, 100); /* Clear out the space */
strcpy(mymsg.text, "Hello, world!");
mymsg.type = 1;
msgsnd(mq_id, &mymsg, sizeof(mymsg), 0);
}
清单 2 中的代码包括了必要的头文件,然后定义了将在 main 函数中使用的变量。第一要务是使用 /tmp/foo 作为命令文件和使用数字 42 作为 ID 来确定 IPC 密钥。出于演示的目的,这里使用 printf(3c) 将密钥显示在屏幕上。接下来,该代码使用 msgget 创建消息队列。msgget 的第一个参数是 IPC 密钥,第二个参数是一组标志。在该示例中,标志包括八进制权限(该权限允许具有 IPC 密钥的任何人完全使用该 IPC)和 IPC_CREAT 标志(此标志导致 msgget 创建队列)。同样,结果被打印到屏幕上。
标签: