PDA

View Full Version : redirecting stdout of child process



frs
07-21-2010, 09:30 AM
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?



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);
}
}

itCbitC
07-21-2010, 09:49 AM
How about redirecting stdin to fd[0], in parent, before reading from it.

salquestfl
07-25-2010, 07:54 PM
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.