[Patch]fdopen() +:fileno()in liolib.c

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

[Patch]fdopen() +:fileno()in liolib.c

Adrian Perez-2

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)

fileno+fdopen.patch (2K) Download Attachment
Reply | Threaded
Open this post in threaded view
|

Re: [Patch]fdopen() +:fileno()in liolib.c

Adrian Perez-2

Adrian Perez wrote :

> 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 ...

.... to interface with Unix file handling functions.

(This phrase was incomplete, sorry).

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