lua-users home
lua-l archive

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


Hello,

I have been modifying the stock Lua 5.1 in order to include Lua scripting
support in a project I started some weeks ago. For better interaction with
lower-level POSIX and Linux APIs I added support for "opening" numerical
file descriptors (via fdopen(3)) with io.open() and a new :fileno() method
for files (obviously enough, uses the fileno(3) function to get a numerical
file descriptor).

I think you may find this patch useful, so I decided to share it. It is
a small patch for Lua 5.1 which modifies liolib.c only. After applying the
patch things like the following can be done:

  if not posix.isatty(io.stderr:fileno()) then
    io.stderr = io.open("/dev/tty", "w") -- Reopen the terminal
    posix.close(2)                       -- Close non-tty stderr
    posix.dup(io.stderr:fileno(), 2)     -- Reassign desriptor 2 to /dev/tty
  end

  if not posix.isatty(io.stdout:fileno()) then
    posix.close(1)                   -- Close error stream
    posix.dup(io.stderr:fileno(), 1) -- This calls dup2()
    io.stderr = io.open(1, "w")      -- Now stderr and stdout are the same
  end

  -- ...

(Note that this even redirects the output of Lua's print() to stderr when
standard output is not a terminal ;-D)

Of course, allowing io.open() to work with a numerical argument could be
dangerous -- but if programmers shoot themselves in their feet, you should
hire better programmers! With this patch it should easier

If someone wants to make comments/suggestions, they will be appreciated.

Cheers,

-- 
Adrian Perez
"Experience is what you gen when you don't get what you want"
                                           -- (Dan Stanford)

Attachment: fileno+fdopen.patch
Description: Binary data