【问题标题】:Redirect stdin in C program to another process将C程序中的stdin重定向到另一个进程
【发布时间】:2010-04-21 03:47:40
【问题描述】:

我有一个 C 程序,我想让它用 tr 过滤所有输入。所以,我想将 tr 作为子进程启动,将我的标准输入重定向到它,然后捕获 tr 的标准输出并从中读取。

编辑:这是我到目前为止的代码,它不起作用。它立即出现段错误,但我不明白为什么:

#include <stdlib.h>
#include <stdio.h>

int main(int argc, char** argv){
  int ch;
  int fd = stripNewlines();

  while((ch = getc(fd)) != EOF){
    putc(ch, stdout);
  }

  return 0;
}

int stripNewlines(){
  int fd[2], ch;
  pipe(fd);

  if(!fork()){
    close(fd[0]);

    while((ch = getc(stdin)) != EOF){
      if(ch == '\n'){ continue; }
      putc(ch, fd[1]);
    }

    exit(0);
  }else{
    close(fd[1]);

    return fd[0];
  }
}

编辑:原来这是两件事:一是我的标头没有将标准输入和标准输出定义为 0 和 1,所以我实际上是在读/写完全随机的管道。另一个是由于某种原因 getc 和 putc 不能按我的预期工作,所以我不得不使用 read() 和 write() 代替。如果我这样做,那就完美了:

#include <stdlib.h>
#include <stdio.h>

int main(int argc, char** argv){
  int ch;
  int fd = stripNewlines();

  while(read(fd, &ch, 1) == 1){
    write(1, &ch, 1);
  }

  return 0;
}

int stripNewlines(){
  int fd[2];
  int ch;
  pipe(fd);

  if(!fork()){
    close(fd[0]);

    while(read(0, &ch, 1) == 1){
      if(ch == '\n'){ continue; }
      write(fd[1], &ch, 1);
    }

    exit(0);
  }else{
    close(fd[1]);
    return fd[0];
  }
}

【问题讨论】:

    标签: c unix stdin


    【解决方案1】:

    stdin 阅读它让生活变得更加困难。如果您可以忍受从另一个FILE * 读取数据,那么使用popen() 生成tr 并从FILE * 读取它会很容易地返回。

    编辑:如果你不能这样做,那么你需要变得有点丑陋。首先使用 popen 生成 tr 并重定向其输出。然后使用fileno 获取与FILE *stdin 关联的文件号。最后,使用dup2stdin 的文件描述符与来自tr 的管道关联起来。

    【讨论】:

    • 是的,这让我不得不问这个问题变得非常困难。如果我能做到这一点,我会的。 :-)
    【解决方案2】:

    popen(3)。基本上你需要做的就是

    FILE *in = popen("tr <args>", "r");
    

    然后从in读取。

    【讨论】:

      【解决方案3】:

      您为什么不能将输入从 tr 管道传输到您的程序?

      tr A-Z a-z | myprogram

      【讨论】:

      • 是的,但是进入起来有点复杂。我想在程序本身内处理所有这些。
      【解决方案4】:
      #include <stdio.h>
      int main()
      {
          char x1[100];
          scanf("%[^\n]",x1); // read entire line from tr i.e., from stdin
          printf("\n%s",x1);
      }
      

      并使用

      tr A-Z a-z |我的程序

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-01-21
        • 2010-11-20
        • 2016-05-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-11-20
        • 2019-08-25
        相关资源
        最近更新 更多