Thread: redirecting stdout of child process

  1. #1
    Registered User
    Join Date
    Jun 2010
    Posts
    29

    redirecting stdout of child process

    I'm attempting to read the messages sent by the child by forking, exec, and redirecting stdout. But the read messages are only printed after the child has finished, why this happens? Has something to do with processor scheduling?

    Code:
     
          int fd[2]; /* pipe */
          if( pipe(fd) !=0 )
          {
    	perror("Failed to create pipe");
    	exit(EXIT_FAILURE);
          }
    
          switch (pid_t cpid= fork() )
          {
    	case -1:
    	  perror("Failed to fork");
    	  exit(EXIT_FAILURE);
    	  break;
    
    	case 0:
    	  if( dup2(fd[1],STDOUT_FILENO) ==-1 )
    	  {
    	    perror("Fail redirecting stdout");
    	    exit(EXIT_FAILURE);
    	  }
    	  close(fd[0]);
    	  close(fd[1]);
    
    	  if(execl("/usr/bin/sixad","sixad","-s",NULL)==-1)
    	    perror("Child unable to execute sixad");
    	  exit(EXIT_FAILURE);
    	  break;
    
    	default:
    	  close(fd[1]);
    	  char buf[500];
    	  while(1)
    	  {
    	    if ( (n = read(fd[0], buf, sizeof(buf))) <= 0)
    	    {
    	      perror("Fail reading from pipe:\n ");
    	      exit(EXIT_FAILURE);
    	    }
    	    printf("Read from pipe:\n %s \nreturn: %d\n",buf,n);
    	  }
          }

  2. #2
    Registered User
    Join Date
    Oct 2008
    Location
    TX
    Posts
    2,059
    How about redirecting stdin to fd[0], in parent, before reading from it.

  3. #3
    Registered User
    Join Date
    Nov 2008
    Posts
    30
    I think in the sixad process, you may be using file stream API which do not write the output till they are explicitly flushed or till newline is written. So, just add fflush for explicit flushing of output.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 6
    Last Post: 05-01-2011, 11:06 AM
  2. Why isn't the execlp() function doing anything?
    By jsrig88 in forum C Programming
    Replies: 5
    Last Post: 10-12-2009, 10:09 AM
  3. Replies: 3
    Last Post: 10-15-2008, 09:24 AM
  4. process programming
    By St0rM-MaN in forum Linux Programming
    Replies: 2
    Last Post: 09-15-2007, 07:53 AM
  5. Redirecting STDOUT to STDIN of a child process
    By 0xception in forum Linux Programming
    Replies: 4
    Last Post: 09-13-2005, 11:58 PM