Recreating stdout/stdin

This is a discussion on Recreating stdout/stdin within the C Programming forums, part of the General Programming Boards category; Hello! For a program I wrote I learned how to redirect stdout from one program to stdin of another program ...

  1. #1
    Registered User
    Join Date
    Apr 2008
    Posts
    40

    Recreating stdout/stdin

    Hello!

    For a program I wrote I learned how to redirect stdout from one program to stdin of another program by using dup() etc. Now I am writing my own shell and it's going pretty well (although I need to change it to use ncurses which I haven't really mastered yet but...), but now I want to add the possibility to use pipes.

    But the problem is while I've learned how to redirect stdoud and stdin I haven't figured out how to restore stdin and stdout again. Could anyone help me?

    What I mean is that if I for example execute from my program (exec*) "ls -l" and pipe it to "grep test". How do I later restore stdin and stdout to go back to putting out output in the terminal and get the input from the keyboard?

  2. #2
    cas
    cas is offline
    Registered User
    Join Date
    Sep 2007
    Posts
    977
    Before you do the redirect, save a copy of your stdout file descriptor, something like:
    Code:
    int stdout_save;
    stdout_save = dup(STDOUT_FILENO); /* save */
    /* redirect, etc */
    dup2(stdout_save, STDOUT_FILENO); /* restore */
    Checking for errors, of course. However, from your description of the program, it sounds like you'll be forking and execing, meaning you can just dup() inside your children and not worry about the parent.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Recreating Clock Code
    By alexisalexus in forum C Programming
    Replies: 2
    Last Post: 03-24-2009, 08:05 PM
  2. Recreating string array from the same variable?
    By Kleid-0 in forum C Programming
    Replies: 4
    Last Post: 12-22-2004, 12:01 AM
  3. Recreating Minesweeper.
    By j0hnb in forum C Programming
    Replies: 15
    Last Post: 02-18-2003, 06:12 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21