繁体   English   中英

将标准输出重定向到管道写入端

[英]redirecting stdout to pipe write end

我正在写一个小程序,这是它应该做的。

在主要过程中,我必须创建一个新程序,并且应该执行另一个仅执行printf(“ text”)程序。 我想在stdout上重定向管道写端,并且主进程应该从其管道读取中读取并在stdout上打印出来。 我编写了代码,但是当父进程尝试从管道读取时,一次又一次出现分段错误。

#include <sys/types.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>

void write_to(FILE *f){
  char buf[50];
  fprintf(f,"KOMA");
}

int main(){
  int cpPipe[2];
  int child1_fd;
  int child2_fd;

  if(pipe(cpPipe) == -1){

    fprintf(stderr,"ERROR PIPE creation");
    exit(1);

  }else{printf("pipe couldn't be created\n");}

  child1_fd = fork();

  if(child1_fd < 0){
    fprintf(stderr, " CHILD creation error");
    exit(1);
  }

  if(child1_fd == 0){
    printf("*CHILD*\n");
    char program[] = "./Damn";
    int dupK;
    printf("stdout %d \n", STDOUT_FILENO);
    printf("stdin %d \n", STDIN_FILENO);
    printf("pipe1 %d \n", cpPipe[1]);
    printf("pipe0 %d \n", cpPipe[0]);

    // closing pipe write
    close(cpPipe[0]);
    close(1);
    dup(cpPipe[1]);

    printf("and");

    close(cpPipe[1]);
    exit(0);
  }else{
    printf("*Parent*\n");
    char *p;
    char *buf;
    FILE *pipe_read;

    close(cpPipe[1]);
    pipe_read = fdopen(cpPipe[0],"r");

    while((buf = fgets(p,30,pipe_read)) != NULL){
      printf("buf %s \n", buf);
    }

    wait();
    printf("Child is done\n");
    fclose(pipe_read);

    exit(0);
  }
}

将stdout重定向到管道时,是否必须关闭管道写入端?

嗯,...您的细分错误的原因在这里:

buf = fgets(p,30,pipe_read);

p表示根本没有重要意义的指针。 它的内容就是执行时堆栈中的内容,您无需对其进行初始化。 您需要它指向可以使用的内存块! 给它分配一个malloc()调用的返回值,或将其声明为char p[LEN]

编辑:您还将重新打开已经打开的文件描述符。 查看关于fgetspipe的文档,我认为您对它们的工作方式感到困惑。

现在,也就是说,您的函数流程有点令人困惑。 尝试澄清它! 请记住,代码旨在表达意图,功能思想。 尝试使用铅笔和纸来组织程序,然后将其编写为实际代码:)。

干杯!

将stdout重定向到管道时,是否必须关闭管道写入端?

通常,是的,因为在管道的写端处于打开状态的进程中,读取管道的进程将不会获得EOF并挂起。 当然,关闭不使用的文件描述符也很整洁。

您的代码还会在成功路径中显示“无法创建管道”。

暂无
暂无

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

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