2

I am relatively new to C, and am working on an assignment in which we are required to write a shell. The shell must have most standard functionality, including file redirection and piping. File redirection must be done using dup2, and I have been encountering problems with this which I cannot find a relevant solution for on Stack Overflow or elsewhere.

I have created a struct which stores a statement to be executed in the shell, as well as input or output redirection file pointers in the variables input_redir and output_redir. If a file pointer is set for either, the file is opened and remains open until used for execution. For each statement, I check whether the input_redir or output_redir file pointers are not NULL, and if so I use dup2 in the relevant way to redirect input or output. My code for this is as follows:

if(pid == 0) {
            if(stat->input_redir != NULL) {
                dup2(fileno(stat->input_redir), STDIN_FILENO);
                fclose(stat->input_redir);
            }

            if(stat->output_redir != NULL) {
                dup2(fileno(stat->output_redir), STDOUT_FILENO);
                fclose(stat->output_redir);
            } ...

Output to files is working perfectly, allowing me to execute commands such as 'echo hello world > testOutput.txt', but input from a file does not work at all, instead printing a blank line and then continuing to wait for the next user input. I have looked at dup2 man pages and can't seem to figure out what is going wrong here - presumably the input is causing an error? I am executing commands using execvp, which should respond to the redirection if I understand correctly.

Many thanks for any help!

  • this question is off topic because when posting a question about a run time problem, as this question is doing, you must post a [mcve] so we can reproduce the problem so we can debug it. – user3629249 Nov 29 '17 at 23:15

0 Answers0