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.

2
  • Do you want yourprogram < datafile to work, or do you want to know how to do equivalent of above inside C, without shell? Commented Jul 6, 2011 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. Commented Jul 6, 2011 at 16:23

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.