lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Mike Pall  writes:
> Ok, so stdin/stdout/stderr can no longer be closed from Lua [5.1.3] code.


It's possible with the debug library.  Here's the hack I posted in
http://lua-users.org/wiki/HiddenFeatures :

  local f = assert(io.open '/dev/null') -- or possibly NUL on Windows
  debug.setfenv(io.stdout, debug.getfenv(f)) -- make closable
  f:close()
  assert(io.stdout:close()) -- succeeds


> E.g. stdin may have been closed from C code or may not be open to
> begin with (for daemon processes, though it's customary to
> freopen() to /dev/null to avoid these kind of problems).


In my case, I have a GUI application where stdin is not really open to begin
with.  Here's the solution I used after applying 5.1.3:

  luaL_openlibs(m_L);

  lua_getglobal(m_L, "io");
  lua_getfield(m_L, -1, "stdin");
  FILE** f = (FILE**)lua_touserdata(m_L, -1);
  *f = NULL;
  lua_pop(m_L, 2);

Now, operations on io.stdin result in the error "attempt to use a closed file".