简体   繁体   English

现在在C中管道IPC

[英]Pipes IPC in C now

For self learning prupose I want to connect 2 programms with pipes. 出于自我学习的目的,我想将2个程序与管道连接起来。 The first program takes input, makes it upper and print to screen, in this example first program gets executed but no input output possible. 第一个程序接受输入,使其上方并打印到屏幕,在此示例中,第一个程序被执行,但没有输入输出。 How I have to change the pipe close() functions in second program to get a result. 我如何在第二个程序中更改管道close()函数以获取结果。

Close output pipe right after writing or modify your first program to fflush(stdout) after each character write (because of buffering nature of std(in|out) second program stucks on read and first program waits for input as it didn't get EOF - close() from second program sends EOF to first, first one terminates and on termination stdout is flushed automatically). 写入后立即关闭输出管道,或者在每次写入字符后将第一个程序修改为fflush(stdout)(由于std(in | out)的缓冲性质,第二个程序在读取时卡住,第一个程序等待输入,因为它没有获得EOF) -第二个程序的close()将EOF发送到第一个,第一个终止,并在终止时自动刷新stdout)。

int main(int argc, char** argv) {
  pid_t pid;
  int fi[2];
  int fo[2];

  char c;

  if (pipe(fi) < 0)
    perror("pipe");
  if (pipe(fo) < 0)
    perror("pipe");

  switch ( fork() ) {
  case -1:
    exit(1);
  case 0:
    dup2(fi[0], STDIN_FILENO);
    close(fi[1]);
    dup2(fo[1], STDOUT_FILENO);
    close(fo[0]);
    execlp("pipes1", "pipes1",(char *)NULL);

  default:
    close(fi[0]);
    close(fo[1]);
    break;
  }

  write(fi[1], "t", 1);
  close(fi[1]);
  read(fo[0], &c, 1);
  printf("%c\n", c);
  close(fo[0]);

  return 0;
}

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

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