dynamic array in c

#include <stdio.h>
#include <stdlib.h>

struct t_array {
	int *buf;
	int cap;
	int len;
};

int array_init(struct t_array *array) {
	if(!array) {
		return -1;
	}
	array->buf = malloc(10 * sizeof(int));
	array->len = 0;
	array->cap = 0;

	if(array->buf) {
		array->cap = 10;
		return 0;
	}
	return -1;
}

int array_reset(struct t_array *array) {
	if(!array) {
		return -1;
	}
	if(!array->buf) {
		return array_init(array);
	}
	array->len = 0;
	return 0;
}

void array_destroy(struct t_array *array) {
	if(!array) {
		return;
	}
	if(array->buf) {
		array->len = 0;
		array->cap = 0;
		free(array->buf);
		array->buf = NULL;
	}
}

int array_push(struct t_array *array, int data) {
	if(!array) {
		return -1;
	}
	if(array->len >= array->cap) {
		int size = array->cap * 2 + 10;
		array->buf = realloc(array->buf, size * sizeof(int));
		array->cap = size;
	}
	if(!array->buf) {
		return -1;
	}
	array->buf[array->len] = data;
	array->len++;
	return 0;
}

int array_pop(struct t_array *array) {
	if (!array || array->len <= 0 || !array->buf) {
		return -1;
	}
	return array->buf[--array->len];
}

int main() {
	struct t_array *array;
	int result, i;

	array_init(array);

	for (int i = 0; i < 100; ++i)
	{
		array_push(array, i);
	}

	for (int i = 0; i < 100; ++i)
	{
		result = array_pop(array);
		printf("%d\n", result);
	}

	array_destroy(array);

	return 0;
}

 

发表在 Linux | 留下评论

C开源hash代码uthash的用法总结

uthash 是C的比较优秀的开源代码,它实现了常见的hash操作函数,例如查找、插入、删除等待。该套开源代码采用宏的方式实现hash函数的相关功能,支持C语言的任意数据结构最为key值,甚至可以采用多个值作为key,无论是自定义的struct还是基本数据类型,需要注意的是不同类型的key其操作接口方式略有不通。

使用uthash代码时只需要包含头文件”uthash.h”即可。由于该代码采用宏的方式实现,所有的实现代码都在uthash.h文件中,因此只需要在自己的代码中包含该头文件即可。可以通过下面两种方式获取源代码:

  • 通过官方下载链接:

https://github.com/troydhanson/uthash

  • 国外网络无法访问的时候,可以从下面网址获取:

http://download.csdn.net/detail/hjx_1000/6539789

  • 另外,uthash的英文使用文档介绍可从下面网址获得:

http://troydhanson.github.io/uthash/userguide.html#_add_item

1.uthash的效率

uthash的插入、查找、删除的操作时间都是常量,当然这个常量的值收到key以及所选择的hash函数的影响,uthash共提供了7中函数函数,一般情况下选择默认的即可。如果对效率要求特别高时,可以再根据自己的需求选择适合自己的hash函数。

2、uthash的使用

在hash操作中,都是按照“键-值“对的方式进行插、查等操作,在uthash中,其基本数据结构就是一个包含“键-值“对的结构体,另外,该结构体中还包含一个uthash内部使用的hash处理句柄,如下代码所示:

#include"uthash.h"
 
struct my_struct {
    int id;                    /* key */
    char name[10];
    UT_hash_handle hh;         /* makes this structure hashable */
};

其中:

  • id是键(key);
  • name是值,即自己要保存的数据域,这里可以根据自己的需要让它变成结构体指针或者其他类型都可以;
  • hh是内部使用的hash处理句柄,在使用过程中,只需要在结构体中定义一个UT_hash_handle类型的变量即可,不需要为该句柄变量赋值,但必须在该结构体中定义该变量。
  •       Uthash所实现的hash表中可以提供类似于双向链表的操作,可以通过结构体成员hh的 hh.prev和hh.next获取当前节点的上一个节点或者下一个节点。

3.Key类型为int的简单示例

1)定义一个键为int类型的hash结构体:
#include "uthash.h"
 
struct my_struct {
    int ikey;                    /* key */
    char value[10];
UT_hash_handle hh;         
     };
     struct my_struct *g_users = NULL;
这里需要注意:
  • key的类型为int,key的类型不一样,后面的插入、查找调用的接口函数就不一样,因此要求确保key的类型与uthash的接口函数一致。
  • 必须提供UT_hash_handle变量hh,无需为其初始化。
  • 定义一个hash结构的空指针users,用于指向保存数据的hash表,必须初始化为空,在后面的查、插等操作中,uthash内部会根据其是否为空而进行不同的操作。

2)实现自己的查找接口函数:

struct my_struct *find_user(int ikey) {
    struct my_struct *s;
HASH_FIND_INT(g_users, &ikey, s );
return s;
}
其实现过程就是先定义一个hash结构体指针变量,然后通过HASH_FIND_INT接口找到该key所对应的hash结构体。这里需要注意:
  • Uthash为整型key提供的查找接口为HASH_FIND_INT
  • 传给接口HASH_FIND_INT的第一个参数就是在1)中定义的指向hash表的指针,传入的第二个参数是整型变量ikey的地址。

3)实现自己的插入接口函数:

void add_user(int ikey, char *value_buf) {
    struct my_struct *s;
    HASH_FIND_INT(g_users, &ikey, s);  /* 插入前先查看key值是否已经在hash表g_users里面了 */
    if (s==NULL) {
      s = (struct my_struct*)malloc(sizeof(struct my_struct));
      s->ikey = ikey;
      HASH_ADD_INT(g_users, ikey, s );  /* 这里必须明确告诉插入函数,自己定义的hash结构体中键变量的名字 */
    }
    strcpy(s-> value, value_buf);
}
由于uthash要求键(key)必须唯一,而uthash内部未对key值得唯一性进行很好的处理,因此它要求外部在插入操作时要确保其key值不在当前的hash表中,这就需要,在插入操作时,先查找hash表看其值是否已经存在,不存在在时再进行插入操作,在这里需要特别注意以下两点:
  • 插入时,先查找,当键不在当前的hash表中时再进行插入,以确保键的唯一性。
  • 需调用插入接口函数时需要明确告诉接口函数,自己定义的键变量的名字是什么。

4)实现删除接口

void delete_user(int ikey) {
    struct my_struct *s = NULL;
    HASH_FIND_INT(g_users, &ikey, s);
    if (s==NULL) {
      HASH_DEL(g_users, s); 
      free(s);            
    }
}

删除操作的接口函数为HASH_DEL,只需要告诉该接口要释放哪个hash表(这里是g_users)里的哪个节点(这里是s),需要注意:释放申请的hash结构体变量,uthash函数只将结构体从hash表中移除,并未释放该结构体所占据的内存。

5)清空hash表

void delete_all() {
  struct my_struct *current_user, *tmp;
 
  HASH_ITER(hh, users, current_user, tmp) {
    HASH_DEL(g_users,current_user);  
free(current_user);            
  }
}
这里需要注意:uthash内部提供了另外一个清空函数:
HASH_CLEAR(hh, g_users);

函数,但它不释放各节点的内存,因此尽量不要使用它,

6)统计hash表中的已经存在的元素数

该操作使用函数HASH_COUNT即可获取到当前hash表中的元素数,其用法为:
unsigned int num_users;
num_users = HASH_COUNT(g_users);
printf("there are %u items\n", num_users);

7、遍历元素
      在开发过程中,可能需要对整个hash表进行遍历,这里可以通过hh.next获取当前元素的下一个元素。具体遍历方法为:
struct my_struct *s, *tmp;
HASH_ITER(hh, g_users, s, tmp) {
    printf("user ikey %d: value %s\n", s->ikey, s->value);
    /* ... it is safe to delete and free s here */
}

另外还有一种不安全的删除方法,尽量避免使用它:
void print_users() {
    struct my_struct *s;
 
    for(s=g_users; s != NULL; s=s->hh.next) {
        printf("user ikey %d: value %s\n", s->ikey, s->value);
    }
}

4. 其他类型key的使用
       本节主要关于key值类型为其他任意类型,例如整型、字符串、指针、结构体等时的用法。
         注意:在使用key值为浮点类型时,由于浮点类型的比较受到精度的影响,例如:1.0000000002被认为与1相等,这些问题在uthash中也存在。
4.1. int类型key
       前面就是以int类型的key作为示例,总结int类型key使用方法,可以看到其查找和插入分别使用专用接口:HASH_FIND_INT和ASH_ADD_INT。
4.2. 字符指针char*类型key与字符数组char key[100]类型key
       特别注意在Strting类型中,uthash对指针char*和字符数组(例如char key[100])做了区分,这两种情况下使用的接口函数时不一样的。在添加的时候,key的类型为指针时使用接口函数HASH_ADD_KEYPTR,key的类型为字符数组时,使用接口函数HASH_ADD_STR,除了添加的接口不一样外,其他的查找、删除、变量等接口函数都是一样的。
4.3.使用地址作为key
          在uthash中也可使用地址做key进行hash操作,使用地址作为key值时,其类型为void*,这样它就可以支持任意类型的地址了。在使用地址作为key时,插入和查找的专用接口函数为HASH_ADD_PTRHASH_FIND_PTR,其余接口是一样的。
4.3.其他非常用类型key
       在uthash中还可使用结构体作为key,甚至可以采用组合的方式让多个值作为key,这些在其官方的网站张均有较详细的使用示例。在使用uthash需要注意以下几点:
  •  在定义hash结构体时不要忘记定义UT_hash_handle的变量
  •  需确保key值唯一,如果插入key-value对时,key值已经存在,再插入的时候就会出错。
  • 不同的key值,其增加和查找调用的接口函数不一样,具体可见第4节。一般情况下,不通类型的key,其插入和查找接口函数是不一样的,删除、遍历、元素统计接口是通用的,特殊情况下,字符数组和字符串作为key值时,其插入接口函数不一样,但是查找接口是一样的。
发表在 Linux | 留下评论

mosquitto 启动脚本

#! /bin/sh
# Based on /etc/init.d/sshd as it came on CentOS 5.6:
#
# Copyright (c) 1995-2000 SuSE GmbH Nuernberg, Germany.
#
# Author: Jiri Smid <feedback@suse.de>

# /etc/init.d/mosquitto
#

### BEGIN INIT INFO
# Provides: mosquitto
# Required-Start: $network $remote_fs
# Required-Stop: $network $remote_fs
# Default-Start: 3 5
# Default-Stop: 0 1 2 6
# Short-Description: Mosquitto MQTT broker
# Description: Mosquitto MQTT broker
### END INIT INFO

MOSQUITTO_BIN=/usr/sbin/mosquitto
test -x $MOSQUITTO_BIN || exit 5
prog="mosquitto"

MOSQUITTO_PIDFILE=/var/run/mosquitto.pid

. /etc/rc.d/init.d/functions

start()
{
	echo -n "Starting Mosquitto MQTT broker"
	## Start daemon with startproc(8). If this fails
	## the echo return value is set appropriate.

	$MOSQUITTO_BIN -d -c /etc/mosquitto/mosquitto.conf && success || failure
	RETVAL=$?
	[ "$RETVAL" = 0 ] && touch /var/lock/mosquitto
        echo
}

stop()
{
	echo -n "Shutting down Mosquitto MQTT broker"
        ## Stop daemon with killproc(8) and if this fails
        ## set echo the echo return value.
	if [ -n "`pidfileofproc $MOSQUITTO_BIN`" ] ; then
        	#killproc -p $MOSQUITTO_PIDFILE -TERM $MOSQUITTO_BIN
		killproc $MOSQUITTO_BIN
	else
		failure $"Stopping $prog"
	fi
	RETVAL=$?

	[ "$RETVAL" = 0 ] && rm -f /var/lock/mosquitto
	echo
}

reload()
{
	echo -n $"Reloading $prog: "
        if [ -n "`pidfileofproc $MOSQUITTO_BIN`" ] ; then
            killproc $MOSQUITTO_BIN -HUP
        else
            failure $"Reloading $prog"
        fi
        RETVAL=$?
        echo
}

case "$1" in
	start)
		start
		;;
	stop)
		stop
		;;
	restart)
		## Stop the service and regardless of whether it was
		## running or not, start it again.
		$0 stop
		$0 start
		;;
	force-reload|reload)
		reload
		;;
	status)
		status -p $MOSQUITTO_PIDFILE mosquitto
		RETVAL=$?
		;;
	*)
	echo "Usage: $0 {start|stop|status|restart|force-reload|reload}"
	exit 1
	;;
esac
exit $RETVAL

 

发表在 Linux | 留下评论

erlang hello world

afile_server.erl

-module(afile_server).
-export([start/1, loop/1]).

start(Dir) -> 
	spawn(afile_server, loop, [Dir]).

loop(Dir) ->
	receive
		{Client, list_dir} ->
			Client ! {self(), file:list_dir(Dir)};
		{Client, {get_file, File}} ->
			Path = filename:join(Dir, File), 
			Client ! {self(), file:read_file(Path)}
	end,
	loop(Dir).

afile_client.erl

-module(afile_client).
-export([ls/1, get_file/2]).

ls(Server) ->
	Server ! {self(), list_dir}, 
	receive
		{Server, FileList} ->
			FileList
	end.

get_file(Server, File) ->
	Server ! {self(), {get_file, File}}, 
	receive
		{Server, Content} ->
			Content
	end.

 

发表在 erlang | 留下评论

Pinyin4j Helper类

package com.mtjst.im.util;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

public class HanyuPinyinHelper {

	public static boolean isChineseCharacter(char c) {
		int i = (int) c;
		return (i >= 0x4e00 && i <= 0x9fa5);
	}

	public static String getPinyin(String str) {

		StringBuffer sb = new StringBuffer();

		char[] ca = str.toCharArray();

		HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();

		format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
		format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
		format.setVCharType(HanyuPinyinVCharType.WITH_V);

		for (int i = 0; i < ca.length; i++) {
			if (isChineseCharacter(ca[i])) {
				try {
					sb.append(PinyinHelper.toHanyuPinyinStringArray(ca[i],
							format)[0]);
				} catch (BadHanyuPinyinOutputFormatCombination e) {
					e.printStackTrace();
				}
			} else {
				sb.append(ca[i]);
			}
		}

		return sb.toString();
	}
}

 

发表在 android | 留下评论

android AutoCompleteTextView 自定义Adapter

package com.mtjst.im.adapter;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;

import com.mtjst.im.R;
import com.mtjst.im.model.District;

public class DistrictAdapter extends BaseAdapter implements Filterable {

	private LayoutInflater inflater;
	private List<District> mOriginalValues;
	private List<District> districts;

	public DistrictAdapter(Context context, List<District> districts) {
		this.inflater = LayoutInflater.from(context);
		this.districts = districts;
	}

	public void refreshData(List<District> districts) {
		this.districts = districts;
		notifyDataSetChanged();
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder viewHolder = null;
		if (convertView == null) {
			viewHolder = new ViewHolder();
			convertView = inflater.inflate(R.layout.item_district, parent,
					false);
			viewHolder.district = (TextView) convertView
					.findViewById(R.id.district);
			convertView.setTag(viewHolder);
		} else {
			viewHolder = (ViewHolder) convertView.getTag();
		}

		District district = this.districts.get(position);

		viewHolder.district.setText(district.getName());
		return convertView;
	}

	class ViewHolder {
		TextView district;
	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return districts.size();
	}

	@Override
	public String getItem(int position) {
		// TODO Auto-generated method stub
		return districts.get(position).getName();
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}

	@Override
	public Filter getFilter() {
		Filter filter = new Filter() {

			@SuppressWarnings("unchecked")
			@Override
			protected void publishResults(CharSequence constraint,
					FilterResults results) {

				districts = (List<District>) results.values;
				notifyDataSetChanged();
			}

			@Override
			protected FilterResults performFiltering(CharSequence constraint) {

				FilterResults results = new FilterResults();
				List<District> FilteredArrList = new ArrayList<District>();

				if (mOriginalValues == null) {
					mOriginalValues = new ArrayList<District>(districts);
				}

				if (constraint == null || constraint.length() == 0) {
					results.count = mOriginalValues.size();
					results.values = mOriginalValues;
				} else {
					constraint = constraint.toString().toLowerCase();
					for (int i = 0; i < mOriginalValues.size(); i++) {
						District data = mOriginalValues.get(i);
						// if (data.getPinyin().startsWith(
						// HanyuPinyinHelper.getPinyin(constraint
						// .toString()))) {
						// FilteredArrList.add(data);
						// }
						FilteredArrList.add(data);
					}
					// set the Filtered result to return
					results.count = FilteredArrList.size();
					results.values = FilteredArrList;
				}
				return results;
			}
		};

		return filter;
	}
}

 

发表在 android | 留下评论

android 编译 volley

设置环境变量

export PATH=$PATH:/Applications/adt-bundle-mac-x86_64-20140702/sdk/platform-tools:/usr/local/ant/bin:/Applications/adt-bundle-mac-x86_64-20140702/sdk/tools

ant去官网下载二进制包, android命令在adt-bundle-mac-x86_64-20140702/sdk/tools下

下载volley源码

https://github.com/mcxiaoke/android-volley/archive/master.zip

进入volley目录

执行

android update project -p . -t android-20 -s

android-20可以执行 android list targets 命令得到

id: 1 or "android-20"
     Name: Android 4.4W
     Type: Platform
     API level: 20
     Revision: 1
     Skins: HVGA, QVGA, WQVGA400, WQVGA432, WSVGA, WVGA800 (default), WVGA854, WXGA720, WXGA800, WXGA800-7in
 Tag/ABIs : no ABIs.

最后执行 ant jar

就会在bin目录生成volley.jar

发表在 android | 留下评论

搜索文件夹内的所有文件里包含某字符串的linux命令

从文件内容查找匹配指定字符串的行:
$ grep “被查找的字符串” 文件名
从文件内容查找与正则表达式匹配的行:
$ grep –e “正则表达式” 文件名
查找时不区分大小写:
$ grep –i “被查找的字符串” 文件名
查找匹配的行数:
$ grep -c “被查找的字符串” 文件名
从文件内容查找不匹配指定字符串的行:
$ grep –v “被查找的字符串” 文件名
从根目录开始查找所有扩展名为.log的文本文件,并找出包含”ERROR”的行
find / -type f -name “*.log” | xargs grep “ERROR”

发表在 Linux | 留下评论

CentOS升级openssl为最新版

wget http://www.openssl.org/source/openssl-1.0.1j.tar.gz
tar zxvf openssl-1.0.1j.tar.gz
cd openssl-1.0.1j.tar.gz
make && make install

mv /usr/bin/openssl /usr/bin/openssl.OFF

mv /usr/include/openssl /usr/include/openssl.OFF

ln -s /usr/local/ssl/bin/openssl /usr/bin/openssl

ln -s /usr/local/ssl/include/openssl /usr/include/openssl

echo “/usr/local/ssl/lib”>>/etc/ld.so.conf

ldconfig -v

openssl version -a

发表在 Linux | 留下评论

mosquitto — an MQTT broker

Name

mosquitto — an MQTT broker

Synopsis

mosquitto [-c config file] [ -d | –daemon ] [-p port number] [-v]

Description

mosquitto is a broker for the MQTT protocol version 3.1.

Options

-c, --config-file
Load configuration from a file. If not given, the default values as described in mosquitto.conf(5) are used.

-d, --daemon
Run mosquitto in the background as a daemon. All other behaviour remains the same.

-p, --port
Listen on the port specified instead of the default 1883. This acts in addition to the port setting in the config file. May be specified multiple times to open multiple sockets listening on different ports. This socket will be bound to all network interfaces.

-v, --verbose
Use verbose logging. This is equivalent to setting log_type to all in the configuration file. This overrides and logging options given in the configuration file.

Configuration

The broker can be configured using a configuration file as described in mosquitto.conf(5) and this is the main point of information for mosquitto. The files required for SSL/TLS support are described in mosquitto-tls(7).

Broker Status

Clients can find information about the broker by subscribing to topics in the $SYS hierarchy as follows. Topics marked as static are only sent once per client on subscription. All other topics are updated every sys_interval seconds. If sys_interval is 0, then updates are not sent.

$SYS/broker/bytes/received
The total number of bytes received since the broker started.

$SYS/broker/bytes/sent
The total number of bytes sent since the broker started.

$SYS/broker/changeset
The repository changeset (revision) associated with this build. Static.

$SYS/broker/clients/active
The number of currently connected clients

$SYS/broker/clients/expired
The number of disconnected persistent clients that have been expired and removed through the persistent_client_expiration option.

$SYS/broker/clients/inactive
The total number of persistent clients (with clean session disabled) that are registered at the broker but are currently disconnected.

$SYS/broker/clients/maximum
The maximum number of active clients that have been connected to the broker. This is only calculated when the $SYS topic tree is updated, so short lived client connections may not be counted.

$SYS/broker/clients/total
The total number of active and inactive clients currently connected and registered on the broker.

$SYS/broker/connection/#
When bridges are configured to/from the broker, common practice is to provide a status topic that indicates the state of the connection. This is provided within $SYS/broker/connection/ by default. If the value of the topic is 1 the connection is active, if 0 then it is not active. See the Bridges section below for more information on bridges.

$SYS/broker/heap/current size
The current size of the heap memory in use by mosquitto. Note that this topic may be unavailable depending on compile time options.

$SYS/broker/heap/maximum size
The largest amount of heap memory used by mosquitto. Note that this topic may be unavailable depending on compile time options.

$SYS/broker/load/connections/+
The moving average of the number of CONNECT packets received by the broker over different time intervals. The final “+” of the hierarchy can be 1min, 5min or 15min. The value returned represents the number of connections received in 1 minute, averaged over 1, 5 or 15 minutes.

$SYS/broker/load/bytes/received/+
The moving average of the number of bytes received by the broker over different time intervals. The final “+” of the hierarchy can be 1min, 5min or 15min. The value returned represents the number of bytes received in 1 minute, averaged over 1, 5 or 15 minutes.

$SYS/broker/load/bytes/sent/+
The moving average of the number of bytes sent by the broker over different time intervals. The final “+” of the hierarchy can be 1min, 5min or 15min. The value returned represents the number of bytes sent in 1 minute, averaged over 1, 5 or 15 minutes.

$SYS/broker/load/messages/received/+
The moving average of the number of all types of MQTT messages received by the broker over different time intervals. The final “+” of the hierarchy can be 1min, 5min or 15min. The value returned represents the number of messages received in 1 minute, averaged over 1, 5 or 15 minutes.

$SYS/broker/load/messages/sent/+
The moving average of the number of all types of MQTT messages sent by the broker over different time intervals. The final “+” of the hierarchy can be 1min, 5min or 15min. The value returned represents the number of messages send in 1 minute, averaged over 1, 5 or 15 minutes.

$SYS/broker/load/publish/dropped/+
The moving average of the number of publish messages dropped by the broker over different time intervals. This shows the rate at which durable clients that are disconnected are losing messages. The final “+” of the hierarchy can be 1min, 5min or 15min. The value returned represents the number of messages dropped in 1 minute, averaged over 1, 5 or 15 minutes.

$SYS/broker/load/publish/received/+
The moving average of the number of publish messages received by the broker over different time intervals. The final “+” of the hierarchy can be 1min, 5min or 15min. The value returned represents the number of publish messages received in 1 minute, averaged over 1, 5 or 15 minutes.

$SYS/broker/load/publish/sent/+
The moving average of the number of publish messages sent by the broker over different time intervals. The final “+” of the hierarchy can be 1min, 5min or 15min. The value returned represents the number of publish messages sent in 1 minute, averaged over 1, 5 or 15 minutes.

$SYS/broker/load/sockets/+
The moving average of the number of socket connections opened to the broker over different time intervals. The final “+” of the hierarchy can be 1min, 5min or 15min. The value returned represents the number of socket connections in 1 minute, averaged over 1, 5 or 15 minutes.

$SYS/broker/messages/inflight
The number of messages with QoS>0 that are awaiting acknowledgments.

$SYS/broker/messages/received
The total number of messages of any type received since the broker started.

$SYS/broker/messages/sent
The total number of messages of any type sent since the broker started.

$SYS/broker/messages/stored
The number of messages currently held in the message store. This includes retained messages and messages queued for durable clients.

$SYS/broker/publish/messages/dropped
The total number of publish messages that have been dropped due to inflight/queuing limits. See the max_inflight_messages and max_queued_messages options in mosquitto.conf(5) for more information.

$SYS/broker/publish/messages/received
The total number of PUBLISH messages received since the broker started.

$SYS/broker/publish/messages/sent
The total number of PUBLISH messages sent since the broker started.

$SYS/broker/retained messages/count
The total number of retained messages active on the broker.

$SYS/broker/subscriptions/count
The total number of subscriptions active on the broker.

$SYS/broker/timestamp
The timestamp at which this particular build of the broker was made. Static.

$SYS/broker/uptime
The amount of time in seconds the broker has been online.

$SYS/broker/version
The version of the broker. Static.

Wildcard Topic Subscriptions

In addition to allowing clients to subscribe to specific topics, mosquitto also allows the use of two wildcards in subscriptions. + is the wildcard used to match a single level of hierarchy. For example, for a topic of “a/b/c/d”, the following example subscriptions will match:

  • a/b/c/d
  • +/b/c/d
  • a/+/c/d
  • a/+/+/d
  • +/+/+/+

The following subscriptions will not match:

  • a/b/c
  • b/+/c/d
  • +/+/+

The second wildcard is # and is used to match all subsequent levels of hierarchy. With a topic of “a/b/c/d”, the following example subscriptions will match:

  • a/b/c/d
  • #
  • a/#
  • a/b/#
  • a/b/c/#
  • +/b/c/#

The $SYS hierarchy does not match a subscription of “#”. If you want to observe the entire $SYS hierarchy, subscribe to $SYS/#.

Note that the wildcards must be only ever used on their own, so a subscription of “a/b+/c” is not valid use of a wildcard. The # wildcard must only ever be used as the final character of a subscription.

Bridges

Multiple brokers can be connected together with the bridging functionality. This is useful where it is desirable to share information between locations, but where not all of the information needs to be shared. An example could be where a number of users are running a broker to help record power usage and for a number of other reasons. The power usage could be shared through bridging all of the user brokers to a common broker, allowing the power usage of all users to be collected and compared. The other information would remain local to each broker.

For information on configuring bridges, see mosquitto.conf(5).

Signals

SIGHUP
Upon receiving the SIGHUP signal, mosquitto will attempt to reload configuration file data, assuming that the -c argument was provided when mosquitto was started. Not all configuration parameters can be reloaded without restarting. See mosquitto.conf(5) for details.

SIGUSR1
Upon receiving the SIGUSR1 signal, mosquitto will write the persistence database to disk. This signal is only acted upon if persistence is enabled.

SIGUSR2
The SIGUSR2 signal causes mosquitto to print out the current subscription tree, along with information about where retained messages exist. This is intended as a testing feature only and may be removed at any time.

Files

/etc/mosquitto/mosquitto.conf
Configuration file. See mosquitto.conf(5).

/var/lib/mosquitto/mosquitto.db
Persistent message data storage location if persist enabled.

/etc/hosts.allow, /etc/hosts.deny
Host access control via tcp-wrappers as described in hosts_access(5).

发表在 Linux | 留下评论