2

I am trying use piping to communicate between a parent and child process in a C program. The problem I'm running into is the input and output are the same, but should instead be modified by running ./program.

int   childFd   = -1;//File Descriptor for child process communication
int   parentFd  = -1;//File Descriptor for parent process communication

void  someFunc(){
  int childPipe[2];//parent process communication to child
  int parentPipe[2];//child process communication to parent

  int READ=0;
  int WRITE=1;

  pipe(childPipe);
  pipe(parentPipe);

  if (fork()==0){ //child process
    dup2(childPipe[WRITE],STDIN_FILENO); //Purpose is to get input from Child Pipe
    close(childPipe[WRITE]);
    dup2(parentPipe[READ],STDOUT_FILENO);//Send output to parent pipe
    close(parentPipe[READ]);

    execl("./program","./program", NULL);//assuming it runs program correctly
  }
  close(childPipe[WRITE])
  close(parentPipe[READ])
  //parent
  dup2(childPipe[WRITE], childFd);//set childFd to the pipe file descriptor for communicating to the child
  dup2(parentPipe[WRITE], parentFd);//set parentFD to the pipe file descriptor for communicating to the parent

}

I was trying to use information from this post Pipes, dup2 and exec(), but I'm using two pipes instead of 1. Am I inadvertently sending the input back to the out with this code?

  • 2
    For one thing `READ=0` is fine, but `WRITE` needs to be `1` – Steve Friedl Mar 17 '20 at 04:15
  • Also, why are you connecting the read end of the pipe to stdout and the write end of the pipe to stdin? The process produces output on stdout which needs to be written to the write end of the pipe. The process reads from stdin, so that should be connected to the end of the pipe you are supposed to read from. – David Schwartz Mar 17 '20 at 04:20

0 Answers0