Jenny
Jenny

Reputation: 1

Continuous writing and reading using pipes with multiple processes

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

Upvotes: 0

Views: 1774

Answers (1)

tkausl
tkausl

Reputation: 14279

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.

Upvotes: 2

Related Questions