繁体   English   中英

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

[英]Continuous writing and reading using pipes with multiple processes

我的代码包含两个过程。 父进程连续从stdin读取单个字符并将其写入管道(无需按Enter)。 子进程从管道读取并写入stdout。 我的父进程已成功写入管道,但子进程未打印输出。

子进程不输出输出的原因是,它停留在父进程的while循环中,并且从不进入子进程的while循环。

当我在Mac上使用“活动监视器”强制退出父进程时,实际上输入的内容会打印出来。 其次是“杀死:9”

有没有一种方法可以修复我的代码,因此每次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

一切正常,没有卡住或任何东西,直到您期望在控制台中输出。 该错误在这两行中:

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

stdin标准输入 您正在写入标准输出

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

为我工作。

暂无
暂无

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

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