LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Redirection (https://www.linuxquestions.org/questions/programming-9/redirection-642194/)

gdsoccer 05-14-2008 02:16 PM

Redirection
 
Upon posting on my old post this morning I realized I had moved to redirection but was still posting in my piping question. Here is my issue with redirection. I can get it to work and actually write the output of something like ls to a file that I type in. The problem is that once I call ls or whatever command my system hangs up and I have to use CTRL-D to get out. Here is what I have currently


Code:

void shellRedirection(char *buf, int index){
    char command[100];
    char outFile[100];
    int filedes, dupped;
    mode_t mode = S_IWUSR;
    int output = STDOUT_FILENO;
    //commandbreak is a function that splits the entire command into it's seperate command. e.g. splits ls > testfile into ls and testfile
    commandBreak(buf, command, outFile, index);
    printf("First Command = %s -- Second Command %s \n",command, outFile);
    filedes = creat(outFile, mode);    //creates the new file
    dupped = dup2(filedes, output);    //sets stdout to same descriptor
    system(command);                  //calls command on host system
    dup2(1, output);                  //should put output back at 1?
   
}

Like I said this command is called from a main based on the fact it contains the > character. I uses system commands instead of commands on my shell because I would figure the system commands would be more trustworthy. Can anyone see what my issue is?

Thanks a bunch

chrism01 05-14-2008 05:46 PM

Well, I can't tell you (as in don't know) what is wrong, BUT I was always under the impression that the point of these exercises is that you're supposed to write the whole thing in C (like the real shell).
Shelling out via system is 'cheating' imho, and definitely not as per the real thing.
Of course, I could be wrong.
:)

gdsoccer 05-14-2008 11:53 PM

hehe, yeah eventually the entire shell will be written but as of now the only working functions are the make file system and the ls commands. In the spirit of more thorough testing I decided to write the commands to the system with the intent of later going back and passing it as a command to my personal shell :)

osor 05-15-2008 12:13 PM

What is output supposed to be? If I understand correctly, output is always 1 (the dup2() call never changes the value of the either argument). What you are trying to accomplish may be done by “saving” the file descriptor before duping it. Alternatively, the more commonly-seen approach is simply to fork() prior to the dup2() so the parent retains all its file descriptors, and only the child will be affected by the redirection.


All times are GMT -5. The time now is 04:26 AM.