I am making simple ANSI C program, that simulates Unix shell. So I am creating child process using fork() and inside child process I am calling exec() to run given (by user) program.
What I need to do is redirect content of file to stdin, so it can be sent to user called program.
Example: cat < file \\user wants run cat and redirect content of that file to it by typing this to my program prompt
I am trying to do so like this:
...child process...
int fd = open(path_to_file, O_RDONLY);
int read_size = 0;
while ((read_size = read(fd, buffer, BUF_SIZE)) != 0) {
write(STDIN_FILENO, buffer, read_size);
}
close(fd);
execlp("cat", ...);
Everything goes fine, content of file is written to stdin, but after reading whole file, cat still waiting for an input (I need to tell cat, that input ended), but I cannot figure how :-(?
Any ideas? Thanks a lot!!!
Within the child process, redirect the standard input to your
open‘ed descriptor prior to callingexeclp, via thedup2(2)system call:You don’t need the
whileloop in the parent sincecatwill read from the newly redirected descriptor by itself.