0

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

在主进程中,我必须创建一个新进程,并且该进程应该执行另一个只执行 printf("text") 的程序。我想重定向标准输出上的管道写入端,主进程应该从它的管道读取中读取并将其打印到标准输出上。我编写了代码,但是当父进程尝试从管道中读取时,我一次又一次地遇到分段错误。

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

当我将标准输出重定向到它时,我是否必须关闭管道写入端?

4

2 回答 2

2

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

buf = fgets(p,30,pipe_read);

p 是一个指向基本上不重要的地方的指针。它的内容是执行时堆栈中的任何内容,您永远不会初始化它。你需要它指向一块你可以使用的内存!将malloc()调用的返回分配给它,或将其声明为char p[LEN].

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

现在,也就是说,您的函数流程有点令人困惑。努力澄清它!请记住,代码旨在表达意图和功能的想法。试着用铅笔和纸来组织你的程序,然后把它写成实际的代码:)。

干杯!

于 2010-11-26T20:23:13.647 回答
2

当我将标准输出重定向到它时,我是否必须关闭管道写入端?

一般来说,是的,因为当有一个进程打开管道的写端时,读取管道的进程不会得到 EOF 并且会挂起。当然,关闭您不会使用的文件描述符也很整洁。

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

于 2010-11-26T20:37:06.923 回答