redirecting stdout of child process

This is a discussion on redirecting stdout of child process within the Linux Programming forums, part of the Platform Specific Boards category; I'm attempting to read the messages sent by the child by forking, exec, and redirecting stdout. But the read messages ...

  1. #1
    frs
    frs is offline
    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,049
    How about redirecting stdin to fd[0], in parent, before reading from it.

  3. #3
    Registered User
    Join Date
    Nov 2008
    Posts
    26
    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, 12:06 PM
  2. Why isn't the execlp() function doing anything?
    By jsrig88 in forum C Programming
    Replies: 5
    Last Post: 10-12-2009, 11:09 AM
  3. Replies: 3
    Last Post: 10-15-2008, 10:24 AM
  4. process programming
    By St0rM-MaN in forum Linux Programming
    Replies: 2
    Last Post: 09-15-2007, 08:53 AM
  5. Redirecting STDOUT to STDIN of a child process
    By 0xception in forum Linux Programming
    Replies: 4
    Last Post: 09-14-2005, 12:58 AM

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