Mona Jalal
Mona Jalal

Reputation: 38145

How to get back to stdout after redirection?

I have implemented a shell which supports redirection but after the redirtection is done it gets of of my shell. How can I manage it in a way to get back to shell (stdout)?

 int i;
     for (i=1; args[i];i++)
         {
           if (strcmp(args[i],">")==0)
             {
               printf("argv[i] %s %d \n", args[i], i);
               int out = open(args[i+1], O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IRGRP | S_IWGRP | S_IWUSR);
               close(1);
               int fdl=dup2(out,1);
               close(out);
               execvp(args[0],args);
            //   open(STDOUT, ">>", \$out); //doesn't work~!
             }

         }

Here's what happens when I execute my shell:

 ./basic_shell 
mysh> pwd > out_pwd
argv[i] > 1 
pwd: ignoring non-option arguments

and it creates out_pwd as expected and writes the pwd result into it. However when I try

mysh>ls > out_ls

I receive this error:

ls cannot access >: No such file or directory

Can you please give me some hints on how to fix it?

Upvotes: 2

Views: 202

Answers (2)

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

Reputation: 215193

Instead of actually transforming file descriptors in your shell process, you want to simply save a representation of the mapping, and perform the replacements in the child after fork but before you exec the command.

Upvotes: 2

Ali Kherad
Ali Kherad

Reputation: 965

First close the handle
Then call AllocConsole in kernel32 / or console api in win 7^ to create console

Upvotes: 0

Related Questions