Quote:
Originally Posted by p00ndawg
yes I actually wanted processes A, B, and C communicating with each other, but I only wanted to pipe a message from a->b->c. I didnt realize I had created 4 processes.
Is there anyway to just create 3 processes? how about a way to just get variable pipes communicating with each other?
|
Sure. The reason you wound up with a total of four processes is because each call to fork() returns twice: once in the original process and once in the new one. So after you make the first call to fork(), there are two processes - both of which go on to call the second fork().
To create a total of three processes, make sure you only fork twice. You can do this by checking the return value of fork() to make sure you're in the process which should fork.
Code:
pid_b = fork();
if (pid_b == 0)
{
/* fork() returned 0, so this is the new process, which I call process B. */
pid_c = fork();
if (pid_c == 0)
{
/* This is process C... */
}
}
Now, if your communication channels only need to be such that A can send messages to B, and B can send messages to C, you wind up with something like this:
Code:
pipe(channel_ab);
pid_b = fork();
if (pid_b > 0)
{
/* Process A... Send messages to B using channel_ab[1] */
close(channel_ab[0]);
write(channel_ab[1], msg, size);
} else if (pid_b == 0) {
/* Process B */
close(channel_ab[1]);
pipe(channel_bc);
pid_c = fork();
if (pid_c > 0)
{
/* Still process B. Receive messages from A using channel_ab[0], send messages to C using channel_bc[1]. */
close(channel_bc[0]);
msg_size = read(channel_ab[0], buffer, size);
write(channel_bc[1], msg, size);
} else if (pid_c == 0) {
/* Process C. Receive messages from B using channel_bc[0]. */
msg_size = read(channel_bc[0], buffer, size);
}
}
'Course there's various error checking and stuff you'd want to do in there that's not shown above - but that's the basic idea.