1

I'm writing a C app that has an embedded lua script in it. The Lua script takes input from STDIN. So when I'm running the script from the shell it's like thus:

lua myscript.lua < datafile*

How do I accomplish this from inside the C code?

Thank you.

daelious
  • 13
  • 2
  • Do you want `yourprogram < datafile` to work, or do you want to know how to do equivalent of above inside C, without shell? – Alexander Gladysh Jul 06 '11 at 16:15
  • A little of both. I probably didn't explain it incredibly well. In the program (which is kind of a wrapper for a parser script in Lua) I'm getting each line from the datafile (or datafiles, potentially this could later be a FIFO named pipe) inside program. I'm wanting after I have each line to send it as stdin to the lua parser. – daelious Jul 06 '11 at 16:23

2 Answers2

1

Use the dup2(2) system call on descriptor 0 (stdin) and on the descriptor returned by open(2) on datafile:

int fd = open("datafile", O_RDONLY);
dup2(fd, 0);
/* reading from stdin now is in fact reading from datafile */

Of course, you need some error-checking in a real-world program.

To implement the behaviour of wildcarding, you may want to look at the readdir(3) library function.

Blagovest Buyukliev
  • 42,498
  • 14
  • 94
  • 130
  • How would I pass the STDIN to the lua_State at that point? That's more along the lines of what I can't figure out. – daelious Jul 06 '11 at 16:06
  • This code changes the STDIN for your program (the one that Lua's reading from, just like everybody else) to be the file descriptor. There's nothing to pass in. – Stuart P. Bentley Jul 15 '11 at 13:11
0

Have you tried to just run your script unmodified (i.e. use io.stdin etc.)? Unless you're doing something fancy on C side, it should work out of the box.

Alexander Gladysh
  • 39,865
  • 32
  • 103
  • 160