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