Unix Programming - Redirecting input from a file

This is Interesting: Free IT Magazines  
Home > Archive > Unix Programming > March 2007 > Redirecting input from a file





You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

Author Redirecting input from a file
Ramon F Herrera

2007-03-15, 1:25 am


I'd like to review my notes, to perform a sanity check, if you will.

I have programmed many cases in which one program sends its output to
another program. In these cases, since at a given time a process needs
to be alive producing the data while the other one is consuming it, we
need to create a pipe. The code goes like this:

pipe(pipefd);

if (fork()) {
close(pipefd[READ]);
close(STDOUT);
dup(pipefd[WRITE]);
}
else {
close(pipefd[WRITE]);
close(STDIN);
dup(pipefd[READ]);
execv(program, arguments);
}

printf("This goes through the pipe to the child\n");


But my question is actually about redirecting the input from a file.
In that case, the pipe should be unnecessary, because the file in
question remains accessible, right? So the code should be something
like:

fd = open("somedata.txt", "r");
close(STDIN);
dup(fd);
execv(program, arguments);

The redirecting is not working for me, so I guess there is something
wrong with my reasoning.

In other words, how does a shell perform something like this:

% program < somedata.txt

-Ramon

Logan Shaw

2007-03-15, 1:25 am

Ramon F Herrera wrote:
> But my question is actually about redirecting the input from a file.
> In that case, the pipe should be unnecessary, because the file in
> question remains accessible, right? So the code should be something
> like:
>
> fd = open("somedata.txt", "r");
> close(STDIN);
> dup(fd);
> execv(program, arguments);
>
> The redirecting is not working for me, so I guess there is something
> wrong with my reasoning.
>
> In other words, how does a shell perform something like this:
>
> % program < somedata.txt


I ran this command on Solaris 8 and looked at the output:

truss -f sh -c 'cat < /etc/resolv.conf'

The trace of the system calls shows that it does an open(),
which returns 3, followed by a close(0) and a fnctl(3, F_DUPFD, 0),
which I believe is exactly equivalent to a dup(), and then
finally an execve().

So I think your general theory is right. I guess my first
question is whether you're really using open(). Your example
gives very fopen()-like arguments, and fopen() and open() are
very different beasts, returning very different types.

If that's not it (and you were just taking a bit of poetic
license), have you thought about using dup2() instead, in order
to guarantee that you are putting the opened file into fd 0
as intended?

- Logan
Sponsored Links






Free braindumps | Software forum | Database administration forum

Copyright 2003 - 2008 webservertalk.com