views:

728

answers:

3

Hi

I've made a program that create 5 pipes and fork 5 processes in a loop. I've managed to send data from the parent to each child processe, when each child processe is overlapped by another program. Each loop is done in the following manner

(parent.c):

// Child process - reads from pipe
if (childpid == 0) {
    dup2(fd[0], 0); // replace stdin with pipe input
    execv("program", arguments);

} else { // Parent process - writes to pipe
    write(fd[1], buffer, strlen(buffer)+1);
}

So now i'm able to get the data that is sent from the parent to the pipe, by reading from STDIN_FILENO in the program the childs executes with execv(...).

Like this (program.c):

char *buffer = (char *)malloc(50);
read(STDIN_FILENO, buffer, 50);

My problem however is, how can I send data back to the parent? I was thinking of something like replacing stdout with the pipe output by using dup2 again, but I can't get it to work. I realise this have to be done before using execv(...) at least.


I'm not sure if that explanation was sufficient so I can make a little image with text : )

This is how it is right now:

  • Parent -> Pipe
  • Pipe -> Child process 1
  • Pipe -> Child process 2
  • Pipe -> ...
  • Pipe -> Child process 5

I want it to be like this.

  • Parent -> Pipe
  • Pipe -> Child process 1
  • Pipe -> Child process 2
  • Pipe -> ...
  • Pipe -> Child process 5
  • Child process 1 -> Parent
  • Child process 2 -> Parent
  • ...
  • Child process 5 -> Parent

Thankful for help!

A: 

I looked around on the internet for a bit. It seems that you can use pipes only to communicate one way. Which makes sense - input from stdin and output to stdout. If you want to have two way communication between your parent and child processes, use sockets. There are other methods to achieve two way IPC. I suggest that you learn more about inter process communication.

All the best.

batbrat
+2  A: 

See this unix programming faq here, look at question 1.4 1.5, maybe using a memory map to allow the parent/child processes to read/write from on both ends...There is an excellent guide to understanding IPC here.

Edit: Thanks to Trent for pointing out a small blip in the typo...I meant 1.5...

Hope this helps, Best regards, Tom.

tommieb75
Do you mean question 1.5?
Trent
@Trent: Whoops, yeah, I meant 1.5...sorry....will edit this accordingly...thanks for pointing it out.
tommieb75
+2  A: 

Pipes are unidirectional, not bidirectional, so a generic solution is to create five more pipes (gak!) for the return data. The parent then needs to use select() system call to know which of the return pipes have data ready for reading.

Oh, and I would have written

    dup2(fd[0], 0); // replace stdin with pipe input
should be
    dup2(fd[0], 0); // replace stdin with output from pipe
and vice versa.

Liek the other replies say, there are other communication methods that may be more appropriate, depending on what you are trying to achieve.

martinwguy