# HG changeset patch # User jbe # Date 1428189426 -7200 # Node ID 38e7bd13200ddb8fd050e4a4da24844e4a941152 # Parent d4265136ce8860eed90a410a627dcdfb7c4e4d88 Use write instead of fwrite for non-blocking I/O diff -r d4265136ce88 -r 38e7bd13200d moonbridge.c --- a/moonbridge.c Sun Apr 05 00:35:11 2015 +0200 +++ b/moonbridge.c Sun Apr 05 01:17:06 2015 +0200 @@ -2484,38 +2484,36 @@ /* 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; + int fd, argc, i; const char *str; size_t strlen; - size_t written; - stream = luaL_checkudata(L, 1, LUA_FILEHANDLE); - file = stream->f; + ssize_t written; + luaL_Buffer buf; + fd = lua_tointeger(L, 1); argc = lua_gettop(L) - 1; for (i=0; iclosef) luaL_error(L, "attempt to use a closed file"); + file = stream->f; + if (fflush(file)) goto moonbr_io_write_nb_error; 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; - } + lua_insert(L, 2); fd = fileno(file); + lua_pushinteger(L, fd); + lua_insert(L, 3); 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)) { + if (lua_pcall(L, lua_gettop(L) - 2, 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); + return lua_gettop(L) - 1; moonbr_io_write_nb_error: { char errmsg[MOONBR_MAXSTRERRORLEN]; diff -r d4265136ce88 -r 38e7bd13200d reference.txt --- a/reference.txt Sun Apr 05 00:35:11 2015 +0200 +++ b/reference.txt Sun Apr 05 01:17:06 2015 +0200 @@ -57,7 +57,8 @@ Alternatively to file descriptors, the tables may contain file handles, in which case the file descriptor is automatically extracted from the file handle -and the file handle's buffer is additionally tested for pending data. +and, in case of waiting for reading, the file handle's buffer is additionally +tested for pending data. Please note that support for non-blocking I/O operations is limited if you use ordinary file handles (as Moonbridge does). It is possible, however, to wait @@ -194,6 +195,11 @@ In case of an I/O error, nil (as first result value) and an error message (as second result value) are returned. +Note: Using this method will automatically flush any unflushed data written +through previous socket.output:write(...) calls. Thus, if any data was +previously written in a blocking fashion and has not been flushed, then the +socket.output:write_nb(...) call may block. + This method is also available for any other Lua file handle.