Note that there are some explanatory texts on larger screens.

plurals
  1. POredirecting stdout to pipe write end
    text
    copied!<p>I'm writing a little program, and here is what it should do.</p> <p>In the main process I have to create a new one and that one should execute another program which only does a printf("text"). I want to redirect the pipe write end on stdout and the main process should read from its pipe read and and print it on stdout. I wrote the code but again and again I get a segmentation fault when the parent process tries to read from the pipe.</p> <pre><code>#include &lt;sys/types.h&gt; #include &lt;stdio.h&gt; #include &lt;string.h&gt; #include &lt;unistd.h&gt; #include &lt;stdlib.h&gt; 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 &lt; 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); } } </code></pre> <p>Do I have to close the pipe write end when I redirect stdout to it?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload