0

What I want to do is basically make standard out of the child process write in the write end of the pipe using dup2 and run pico using execvp and the parent would read the read end of the file and do something with it and write it out in the standard out and display it in pico. This is run under a Linux machine.

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
int main(int argc,char* argv[])
{

   char* arguments[] = {"pico", "a.txt", NULL};

   int my_pipe[2];
   if(pipe(my_pipe)==-1)
      fprintf(stderr,"Error\n");

   pid_t child_id;
   child_id = fork();
   if(child_id == -1)
   {
       fprintf(stderr, "Fork error\n");
   }
   if(child_id==0)
   {
       close(my_pipe[0]);
       dup2(my_pipe[1],1); /*make standard out write in the write end of the pipe?*/
       close(my_pipe[1]);
       execvp("pico",arguments);

       fprintf(stderr, "Exec failed\n");
       exit(0);

   }
    close(my_pipe[1]);
    char reading_buf[1];
    char r[] = "S";
    while(read(my_pipe[0], reading_buf,1)>0)/*read something in the pipe*/
    {

        write(1,r,1);/*display "S" in pico*/


    }
    close(my_pipe[0]);



return 0;


}  /* end main */

the problem I'm having is that when I try to do the write() in standard out, pico wouldnt show in the terminal and I got this weird output of continuous "S" (from r) like this:

SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS

and it would add more "S" 's whenever I try to press any key. I'm pretty new to all of this and any help would be appreciated.

Jonas
  • 121,568
  • 97
  • 310
  • 388
yellow
  • 1
  • 1

1 Answers1

0

I think I know what's going on here: because stdout is redirected to the pipe, when pico tries to print to stdout it's actually printing to the pipe and nothing shows up on the screen. You have to manually print to stdout in the parent. Try changing "write(1,r,1)" to "write(1, reading_buf, 1)" and pico will display normally.

UM3430
  • 1
  • 1