Reputation: 41
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:
I want it to be like this.
Thankful for help!
Upvotes: 4
Views: 10223
Reputation: 34592
See this unix programming faq here, look at question 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.
Upvotes: 2
Reputation: 489
If you want to keep using pipes, then make one group of FDs for child->parent communication and one for parent->child communication. So instead of having int fd[2], you have int toParent[2], toChild[2]. Instead of dup2(fd[0], 0), you have dup2(toChild[0], 0); dup2(toParent[1], 1).
And don't just dup, but close the FDs you aren't using.
Upvotes: 0
Reputation: 972
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 inputshould be
dup2(fd[0], 0); // replace stdin with output from pipeand vice versa.
Like the other replies say, there are other communication methods that may be more appropriate, depending on what you are trying to achieve.
Upvotes: 4
Reputation: 5231
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.
Upvotes: 0