0
votes

My code consists of two processes. The parent process continuously reads a single char from stdin and write to the pipe (without the need to press ENTER). The child process reads from the pipe and writes to stdout. My parent process successfully writes to the pipe, but child process isn't printing the output.

The reason the child process isn't printing out the output is because it's stuck in the while loop of the parent process and never enters the child process's while loop.

When I force quit the parent process using the Activity Monitor on my mac, what I typed in actually gets printed out. Followed by "Killed:9"

Is there a way to fix my code so each time the Parent(Input)receives a character, the Child(Output) prints each char out without getting stick in the while loop of the parent process?

char input() {
  char input = getchar();
  return input;
}

int main(void) {

  int inputOutputFd[2];
  pid_t childpid = 0;

  system("/bin/stty raw igncr -echo");

  if(pipe(inputOutputFd) < 0) {
    perror("Failed to create pipe");
    return 1;
  }

  if((childpid = fork()) == -1) {
    perror("Failed to fork input child");
    return 1;
  }

//parent's code -INPUT
  if (childpid > 0) {
    close(inputOutputFd[0]);
    printf("Please enter a word or phrase");

    while(1) {
      char inputChar = input();
      write(inputOutputFd[1], &inputChar, sizeof(inputChar));
    }

    close(inputOutputFd[1]);
    wait(NULL);

  } else { 

//child -OUTPUT
    char outputChar;
    close(inputOutputFd[1]);
    while (read(inputOutputFd[0], &outputChar, sizeof(outputChar)) > 0) 
    {
      printf("%c", outputChar);
      fflush(stdin);
    }
  } //END OF IF-ELSE LOOP
}//END MAIN
1
The reason the child process isn't printing out the output is because it's stuck in the while loop of the parent process and never enters the child process's while loop. Huh? You sure about that? It doesn't even enter the parent's while loop. - tkausl
it does enter the parent's while loop. i've added a printf() inside the parent's while(1) loop. I took out all those printf statements so it code looks less messy. - Jenny
Yeah the parent enters the parent's while loop, but the child doesn't. - tkausl
why does the child need to enter the parent's while loop? it's another process. it only needs to read from the pipe which the parent wrote to. - Jenny
It doesn't need to and it doesn't do. I'm confused. You said it enters the parents while loop, but it doesn't. Or I just misunderstood the sentence I quoted in my initial comment. - tkausl

1 Answers

2
votes

Everything works fine, there is nothing stuck or anything, until you're expecting output in your console. The bug is in those two lines:

  printf("%c", outputChar);
  fflush(stdin);

stdin is standard input. You are writing to standard output.

  printf("%c", outputChar);
  fflush(stdout);

works for me.