# HG changeset patch # User jbe # Date 1428186911 -7200 # Node ID d4265136ce8860eed90a410a627dcdfb7c4e4d88 # Parent 9fff0cb4fc65dee29de3f69e31a06e701c182b00 Work on write_nb method diff -r 9fff0cb4fc65 -r d4265136ce88 moonbridge.c --- a/moonbridge.c Sat Apr 04 23:32:24 2015 +0200 +++ b/moonbridge.c Sun Apr 05 00:35:11 2015 +0200 @@ -978,7 +978,7 @@ /* Lua method for socket object to write to output stream using write_nb */ static int moonbr_child_lua_write_nb_stream(lua_State *L) { - lua_getfield(L, 1, "input"); + lua_getfield(L, 1, "output"); lua_getfield(L, -1, "write_nb"); lua_insert(L, 1); lua_replace(L, 2); @@ -2483,8 +2483,74 @@ } /* New methods for Lua file objects: non-blocking writing */ +static int moonbr_io_write_nb_impl(lua_State *L) { + luaL_Stream *stream; + FILE *file; + int argc, i; + const char *str; + size_t strlen; + size_t written; + stream = luaL_checkudata(L, 1, LUA_FILEHANDLE); + file = stream->f; + argc = lua_gettop(L) - 1; + for (i=0; iclosef) luaL_error(L, "attempt to use a closed file"); + lua_pushcfunction(L, moonbr_io_write_nb_impl); + lua_insert(L, 1); + file = stream->f; + if (ferror(file)) { + lua_pushnil(L); + lua_pushliteral(L, "Previous error condition on file handle"); + return 2; + } + fd = fileno(file); + flags = fcntl(fd, F_GETFL, 0); + if (flags == -1) goto moonbr_io_write_nb_error; + if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1) goto moonbr_io_write_nb_error; + if (lua_pcall(L, lua_gettop(L) - 1, LUA_MULTRET, 0)) { + fcntl(fd, F_SETFL, flags); + return lua_error(L); + } + if (fcntl(fd, F_SETFL, flags) == -1) goto moonbr_io_write_nb_error; + return lua_gettop(L); + moonbr_io_write_nb_error: + { + char errmsg[MOONBR_MAXSTRERRORLEN]; + strerror_r(errno, errmsg, MOONBR_MAXSTRERRORLEN); /* use thread-safe call in case child created threads */ + return luaL_error(L, "Unexpected error in write_nb method: %s", errmsg); + } } /* New global function timeout(...) */