← Back to team overview

mosquitto-users team mailing list archive

using libmosquitto in an external event loop

 

Hello list,

I'm currently writing Lua bindings for libmosquitto [1]. Since Lua does not support preemptive multithreading, using mosquitto_loop_start is not an option. As suggested in the libmosquitto documentation, I'm integrating mosquitto_loop_read/write/misc into a Lua event loop instead. The basic functionality works ok. However, when a network error occurs or the broker shuts down, the event loop starts busy looping. strace output:

poll([{fd=5, events=POLLIN}, {fd=6, events=POLLIN}], 2, -1) = 1 ([{fd=6, revents=POLLIN}])
read(6, "", 1)                          = 0
poll([{fd=5, events=POLLIN}, {fd=6, events=POLLIN}], 2, -1) = 1 ([{fd=6, revents=POLLIN}])
read(6, "", 1)                          = 0

...

stracing the libmosquitto event loop:
[pid 12721] select(4, [3], [], NULL, {1, 0}) = 1 (in [3], left {0, 332713})
[pid 12721] read(3, "", 1)              = 0
[pid 12721] close(3)                    = 0

Looking at the mosquitto_loop code shows that if a read or write error occurs, the socket is closed with the private _mosquitto_socket_close function, which updates the internal mosq state as well. This means that the current libmosquitto API doesn't allow a proper implementation in an external event loop. Making _mosquitto_socket_close public would be a start. Integrating the rc handling of:
* rc = mosquitto_loop_read(mosq, max_packets)
* rc = mosquitto_loop_write(mosq, max_packets)
inside these public functions could be an even cleaner approach.

Would such a code change be an option?

[1] https://github.com/flukso/flm02/tree/rfm12/openwrt/package/lua-mosquitto/src


Cheers
/Bart


Follow ups