2010-11-26 127 views
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); 
    } 
} 

当我将stdout重定向到它时,是否必须关闭管道写入结束?

+0

相关http://stackoverflow.com/questions/4127567/linux-c-run-and-communicate-with-new-process/4127696#4127696 – 2010-11-26 21:01:12

回答

2

嗯......你分段错误的原因是在这里:

buf = fgets(p,30,pipe_read); 

p是一个指针基本上无处重要性。它的内容是在执行时堆栈中的任何内容,你永远不会初始化它。你需要它来指向你可以使用的大量内存!分配一个malloc()呼叫的回报,或将其声明为char p[LEN]

编辑:你也重新打开已经打开的文件描述符。检查文档fgetspipe,我认为你对他们如何工作感到困惑。

现在,这就是说,你的函数的流程有点混乱。尝试澄清它!请记住,代码旨在表达意图,功能的想法。尝试使用铅笔和纸张来组织你的程序,然后把它写成实际的代码:)。

干杯!

+0

谢谢。我用fgets和p来解决这个问题。关于描述符,我不确定你的意思。我对此很着急,这是24小时的分叉,管理和学习的成果。 :) – Robin 2010-11-26 22:28:20

2

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

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

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

+0

是的,那是一个错误,我很着急。谢谢。 – Robin 2010-11-26 20:44:28

相关问题