简单的Posix 消息队列基础练习

根据Unix网络编程卷2进程间通信中的Posix消息通信一章编写一些简单的例子,发现了不少看书时疏忽的地方,特做此笔记:

编写代码如下:

#include 
#include 
#include 
//一个简单的创建一个消息队列的例子,Posix消息队列至少具有随内核的持续性。

#define FILE_MODE (S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH)//注意是小括号
int main(int argc,char * argv[])
{
	int c,flags;
	mqd_t mqd;
	flags=O_RDWR|O_CREAT;
	while((c=getopt(argc,argv,"e"))!=-1)
	{
		switch(c)
		{
			case 'e'://排它性创建选项
				flags|=O_EXCL;
				break;
		}
	}
	if(optind!=argc-1)//getopt在optind中存放下一个待处理参数的下标
	{
		printf("usage:mqcreate [-e] ");
		exit(1);
	}
	if((mqd=mq_open(argv[optind],flags,FILE_MODE,NULL))==-1)
	{
	      perror("mq_open wrong!");
		exit(1);
	}
	if((mq_close(mqd))==-1)
	{
		perror("mq_close wrong!");
		exit(1);
	}
	exit(0);
}
使用gcc命令编译出现错误:

undefined reference to `mq_open'

undefined reference to `mq_close'

通过 man mq_overview找到以下内容:

Linking
Programs using the POSIX message queue API must be compiled with cc -lrt to link against the real-time library, librt.

加上 -lrt编译正确。

通过man mq_overview命令还发现mq_open函数中的第一个参数必须是以‘/’开头且只能含有一个'/',运行完后,只能通过以下方式在文件系统中查看创建的消息队列文件:

[root@Kunge ~]# mkdir /dev/mqueue
[root@Kunge ~]# mount -t mqueue none /dev/mqueue
[root@Kunge ~]# ls /dev/mqueue/

具体原文解释见下:

Message queues are created and opened using mq_open(3); this function returns a message queue descriptor (mqd_t), which is used to refer to the
open message queue in later calls. Each message queue is identified by a name of the form /somename; that is, a null-terminated string of up to
NAME_MAX (i.e., 255) characters consisting of an initial slash, followed by one or more characters, none of which are slashes. Two processes
can operate on the same queue by passing the same name to mq_open(3).

Mounting the message queue file system
On Linux, message queues are created in a virtual file system. (Other implementations may also provide such a feature, but the details are
likely to differ.) This file system can be mounted (by the superuser) using the following commands:

# mkdir /dev/mqueue
# mount -t mqueue none /dev/mqueue

The sticky bit is automatically enabled on the mount directory.

After the file system has been mounted, the message queues on the system can be viewed and manipulated using the commands usually used for files
(e.g., ls(1) and rm(1)).

The contents of each file in the directory consist of a single line containing information about the queue:

$ cat /dev/mqueue/mymq
QSIZE:129 NOTIFY:2 SIGNO:0 NOTIFY_PID:8260

These fields are as follows:

QSIZE Number of bytes of data in all messages in the queue.

NOTIFY_PID
If this is non-zero, then the process with this PID has used mq_notify(3) to register for asynchronous message notification, and the
remaining fields describe how notification occurs.

NOTIFY Notification method: 0 is SIGEV_SIGNAL; 1 is SIGEV_NONE; and 2 is SIGEV_THREAD.

SIGNO Signal number to be used for SIGEV_SIGNAL.





你可能感兴趣的:(Linux,UNP_IPC)