3

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

1 Answer 1

5

Within the child process, redirect the standard input to your open'ed descriptor prior to calling execlp, via the dup2(2) system call:

dup2(fd, 0); execlp("cat", ...); 

You don't need the while loop in the parent since cat will read from the newly redirected descriptor by itself.

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

3 Comments

Great! Thanks a lot man. And could I also manage this command? 'cat < file > out_file' using dup2(...) function?
Yes, you would just need an additional dup2(fd_out, 1).
Are you still calling close prior to execlp?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.