exec family with a file input
Hey guys I am trying to write a shell with C++ and I am having trouble with the function of using input file with the exec commands. For example, the bc shell in Linux is able to do “bc < text.txt” which calculate the lines in the text in a batch like fashion. I am trying to do likewise with my shell. Something along the lines of:
char* input = “input.txt”;
execlp(input, bc, …..) // I don’t really know how to call the execlp command and all the doc and search have been kind of cryptic for someone just starting out.
Is this even possible with the exec commands? Or will I h开发者_StackOverflow社区ave to read in line by line and run the exec commands in a for loop??
You can open the file and then dup2()
the file descriptor to standard input, or you can close standard input and then open the file (which works because standard input is descriptor 0 and open()
returns the lowest numbered available descriptor).
const char *input = "input.txt";
int fd = open(input, O_RDONLY);
if (fd < 0)
throw "could not open file";
if (dup2(fd, 0) != 0) // Testing that the file descriptor is 0
throw "could not dup2";
close(fd); // You don't want two copies of the file descriptor
execvp(command[0], &command[0]);
fprintf(stderr, "failed to execvp %s\n", command[0]);
exit(1);
You would probably want cleverer error handling than the throw
, not least because this is the child process and it is the parent that needs to know. But the throw
sites mark points where errors are handled.
Note the close()
.
the redirect is being performed by the shell -- it's not an argument to bc
. You can invoke bash (the equivalent of bash -c "bc < text.txt"
)
For example, you can use execvp
with a file argument of "bash"
and argument list
"bash"
"-c"
"bc < text.txt"
精彩评论