
07-01-2009
|
|
Registered User
|
|
|
Join Date: Jun 2009
Posts: 8
|
|
Quote:
Originally Posted by tetsujin
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.
|
oh ok thanks alot, I think i understand now . I have a project coming up where ill need to use some pipes and I this really fills in some of my blanks.
thanks again.
|