【问题标题】:Pipes IPC in C now现在在 C 中管道 IPC
【发布时间】:2012-05-05 21:14:01
【问题描述】:

出于自学目的,我想用管道连接 2 个程序。 第一个程序接受输入,将其置顶并打印到屏幕上,在此示例中,第一个程序被执行但没有输入输出可能。我必须如何更改第二个程序中的管道 close() 函数才能获得结果。

【问题讨论】:

  • 您一次从管道读取多少字节?我认为这是关键。 input[read(fi[0], input,100)] = 0; 也很危险——你认为 input[-1] = 0; 会做什么?
  • 您没有显示第二个进程的代码。你的read() 是否在循环中终止,当它得到EOF 时?
  • 第二个程序的目的是什么?它是否调用第一个并要求它制作 TOUPPER("t")?第一个按预期工作。

标签: c ipc pipe


【解决方案1】:

在写入后立即关闭输出管道,或在每个字符写入后将您的第一个程序修改为 fflush(stdout)(因为 std(in|out) 第二个程序的缓冲性质卡在读取上,第一个程序等待输入,因为它没有t 获取 EOF - 第二个程序的 close() 将 EOF 发送到第一个,第一个终止并在终止时自动刷新标准输出。

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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多