Thread: redirecting stdout to a socket

  1. #1
    zsaniK Kinasz's Avatar
    Join Date
    Jan 2003
    Posts
    222

    redirecting stdout to a socket

    I am trying to redirect stdout to a socket, I am not sure if it is possible but here is what I've got

    Code:
    	stdout = fdopen( connect_sckt, "r+" );
    	execl("/bin/cat", "cat", "./document", 0 );
    This doesnt work, any ideas?
    "Assumptions are the mother of all **** ups!"

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    It goes something like this.
    Since you're using execl, best create a fork() process

    Code:
    // sockfd is your already open socket for writing to
    if ( fork() == 0 ) {
        close ( 1 );    // close existing stdout
        dup( sockfd );  // make sockfd the new stdout
        execl("/bin/cat", "cat", "./document", (const char*)0 );
    }
    And yes, that cast at the end is necessary (one of the rare cases). execl() is a variadic function, so a simple 0 is assumed to be an int (not automatically cast to a pointer).
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    zsaniK Kinasz's Avatar
    Join Date
    Jan 2003
    Posts
    222
    And yes, that cast at the end is necessary (one of the rare cases). execl() is a variadic function, so a simple 0 is assumed to be an int (not automatically cast to a pointer).
    Didnt know that, helpful info, and thanx for the solution.

    Out of curiosity, why should you use fork before execl?

    I think i can guess the answer but a proper explanation would be good.
    "Assumptions are the mother of all **** ups!"

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Redirecting stdout to socket
    By rancor in forum C Programming
    Replies: 9
    Last Post: 10-18-2008, 05:18 AM
  2. redirecting stdout
    By ichijoji in forum C++ Programming
    Replies: 2
    Last Post: 08-15-2006, 09:20 PM
  3. Problems with switch()
    By duvernais28 in forum C Programming
    Replies: 13
    Last Post: 01-28-2005, 10:42 AM
  4. redirecting stdout
    By gregulator in forum C Programming
    Replies: 2
    Last Post: 04-22-2004, 10:07 AM
  5. redirecting stdout
    By Draco in forum C Programming
    Replies: 13
    Last Post: 10-11-2003, 12:56 AM