简体   繁体   English

使用具有多个过程的管道连续写入和读取

[英]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). 父进程连续从stdin读取单个字符并将其写入管道(无需按Enter)。 The child process reads from the pipe and writes to stdout. 子进程从管道读取并写入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. 子进程不输出输出的原因是,它停留在父进程的while循环中,并且从不进入子进程的while循环。

When I force quit the parent process using the Activity Monitor on my mac, what I typed in actually gets printed out. 当我在Mac上使用“活动监视器”强制退出父进程时,实际上输入的内容会打印出来。 Followed by "Killed:9" 其次是“杀死: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? 有没有一种方法可以修复我的代码,因此每次Parent(Input)接收到一个字符时,Child(Output)都会打印出每个字符,而不会陷入父进程的while循环中?

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

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 . stdin标准输入 You are writing to standard output . 您正在写入标准输出

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

works for me. 为我工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM