[OpenWrt-Devel] [PATCH 3/5] Support delete a fd event.

xfguo at credosemi.com xfguo at credosemi.com
Fri Jun 20 07:31:19 EDT 2014


When you call the fd_add, it will return an object with `delete` method.
So you can delete that event if you want.

Signed-off-by: Xiongfei(Alex) Guo <xfguo at credosemi.com>
---
 examples/uloop-example.lua | 17 ++++++++++++++---
 lua/uloop.c                | 30 ++++++++++++++++++++++++++++++
 2 files changed, 44 insertions(+), 3 deletions(-)

diff --git a/examples/uloop-example.lua b/examples/uloop-example.lua
index ba34ec5..9b0684e 100755
--- a/examples/uloop-example.lua
+++ b/examples/uloop-example.lua
@@ -46,20 +46,31 @@ uloop.timer(
 	end, 2000
 )
 
-uloop.fd_add(udp, function(ufd, events)
+udp_ev = uloop.fd_add(udp, function(ufd, events)
 	local words, msg_or_ip, port_or_nil = ufd:receivefrom()
 	print('Recv UDP packet from '..msg_or_ip..':'..port_or_nil..' : '..words)
+	if words == "Stop!" then
+		udp_ev:delete()
+	end
 end, uloop.ULOOP_READ)
 
+udp_count = 0
 udp_send_timer = uloop.timer(
 	function()
 		local s = socket.udp()
-		local words = 'Hello!'
+		local words
+		if udp_count > 3 then
+			words = "Stop!"
+			udp_send_timer:cancel()
+		else
+			words = 'Hello!'
+			udp_send_timer:set(1000)
+		end
 		print('Send UDP packet to 127.0.0.1:8080 :'..words)
 		s:sendto(words, '127.0.0.1', 8080)
 		s:close()
 
-		udp_send_timer:set(1000)
+		udp_count = udp_count + 1
 	end, 3000
 )
 
diff --git a/lua/uloop.c b/lua/uloop.c
index c71d537..df57b8a 100644
--- a/lua/uloop.c
+++ b/lua/uloop.c
@@ -172,6 +172,24 @@ static int get_sock_fd(lua_State* L, int idx) {
 	return fd;
 }
 
+static int ul_ufd_delete(lua_State *L)
+{
+	struct lua_uloop_fd *ufd = lua_touserdata(L, 1);
+
+	uloop_fd_delete(&ufd->fd);
+	lua_getglobal(state, "__uloop_cb");
+	luaL_unref(L, -1, ufd->r);
+	lua_getglobal(state, "__uloop_fds");
+	luaL_unref(L, -1, ufd->fd_r);
+
+	return 1;
+}
+
+static const luaL_Reg ufd_m[] = {
+	{ "delete", ul_ufd_delete },
+	{ NULL, NULL }
+};
+
 static int ul_ufd_add(lua_State *L)
 {
 	struct lua_uloop_fd *ufd;
@@ -205,6 +223,18 @@ static int ul_ufd_add(lua_State *L)
 	lua_pop(L, 1);
 
 	ufd = lua_newuserdata(L, sizeof(*ufd));
+
+	lua_createtable(L, 0, 2);
+	lua_pushvalue(L, -1);
+	lua_setfield(L, -2, "__index");
+	lua_pushcfunction(L, ul_ufd_delete);
+	lua_setfield(L, -2, "__gc");
+	lua_pushvalue(L, -1);
+	lua_setmetatable(L, -3);
+	lua_pushvalue(L, -2);
+	luaI_openlib(L, NULL, ufd_m, 1);
+	lua_pushvalue(L, -2);
+
 	memset(ufd, 0, sizeof(*ufd));
 
 	ufd->r = ref;
-- 
1.9.1
_______________________________________________
openwrt-devel mailing list
openwrt-devel at lists.openwrt.org
https://lists.openwrt.org/cgi-bin/mailman/listinfo/openwrt-devel



More information about the openwrt-devel mailing list