lua-users home
lua-l archive

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



On 4-Mar-07, at 10:22 PM, Theodor-Iulian Ciobanu wrote:

This  was  the first thing I tried. Unfortunately, it doesn't work for
me,  as I want/need all input/output redirected. While functions using
io.std*  will  have  indeed  these  streams redirected, those that use
directly std* from C runtime (like print and os.execute() given in the
example) will still output to the screen instead of file.

You can handle the case of print() pretty simply:

function print(first, ...)
  io.stdin:write(tostring(first))
  local n = select("#", ...)
  if n > 0 then
    local t = {...}
    for i = 1, n do io.stdin:write("\t", tostring(t[i])) end
  end
  io.stdin:write"\n"
end

That's the only Lua built-in which uses stdout, and there are
none which use stdin or stderr; all of that stuff is in the
io library.

Of course, as you say, that won't redirect os.execute(). (Does
standard C guarantee that changes to stdin, stdout and stderr
be reflected in the command processor used by system()? Does
Posix even guarantee that?)

In any event, if you want to freopen stdin (and friends),
I suggest you just do that. There's no point creating a new
Lua "file" object; once stdin is redirected, io.stdin will
be automatically redirected. (If it isn't, then the redirection
of print() won't work either.)

I think your program is crashing on exit because the userdata
you create (unnecessarily, I believe, as above) doesn't have
the correct environment table, so it crashes when the __gc
metamethod tries to close the stream.

My guess as to why you are not getting any output is that
whatever filesystem you are using does not fsync() files
on every write(). So even though it's not buffered by the
C library, the internal buffers are not committed to disk.
That's just a guess, though.