printf to pipe

This is a discussion on printf to pipe within the C Programming forums, part of the General Programming Boards category; I am trying to figure out how pipes work so I have this code: Code: int main(){ int fdpipe[2]; pipe(fdpipe); ...

  1. #1
    Registered User
    Join Date
    Oct 2007
    Posts
    5

    printf to pipe

    I am trying to figure out how pipes work so I have this code:
    Code:
    int main(){
            int fdpipe[2];
            pipe(fdpipe);
            if(fork()!=0){//parent
                    dup2(fdpipe[1],1);
                    close(fdpipe[0]);
                    printf("mplamplampla\n"); 
                    int status;
                    waitpid(-1,&status,0);
            }
            else{
                    dup2(fdpipe[0],0);
                    close(fdpipe[1]);
                    char buf[100];
                    read(stdin,buf,7);
                    printf("read from input:%s\n",buf);
            }
    }
    what i am trying to do is having the parent process write something to the pipe and child process read from the pipe. But the child process just hangs without printing any output.
    Now, if i change the
    Code:
    printf("mplampla\n")
    with
    Code:
    write(1,"mplampla\n",10);
    works fine. child prints:
    read from input:mplampla

    Isn't printf writing to file with filedescriptor 1, output?
    thanks

  2. #2
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    You probably need to use
    Code:
      fclose(stdout);
      stdout = fdopen(1);
    http://www.hmug.org/man/3/fdopen.php

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. IF CONDITION plese help
    By birumut in forum C Programming
    Replies: 12
    Last Post: 03-06-2009, 09:48 PM
  2. making it portable.....?
    By ShadeS_07 in forum C Programming
    Replies: 11
    Last Post: 12-24-2008, 09:38 AM
  3. get keyboard and mouse events
    By ratte in forum Linux Programming
    Replies: 10
    Last Post: 11-17-2007, 05:42 PM
  4. Simple C question: user input to repeat a loop
    By evernaut in forum C Programming
    Replies: 2
    Last Post: 11-18-2006, 09:23 AM
  5. Drawing tables in C
    By stanoman in forum C Programming
    Replies: 5
    Last Post: 10-09-2003, 11:14 AM

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