PDA

View Full Version : Multiple processes from one Parent using fork() in C



ArcadeEdge
04-28-2012, 05:48 PM
So I'm trying to write this program that requires only the parent to fork multiple process that will all do the same time.

I am able to generate 3 processes, but only two are from the parent and other one is a result of one of the children's.



printf("Parent = %d\n", getpid());
for(i=0;i<2;i++) {
if((pid[i] = fork()) == 0 ) {
pid = getpid();
printf("\tChild = %d\n", pid);
printf("I JUST GOT FORKED %d\n", getpid());
}
else
printf("I AM PARENT %d\n", getpid());
}



Output:



Parent = 9727
I AM PARENT 9727
Child = 9728
I JUST GOT FORKED 9728
I AM PARENT 9727
I AM PARENT 9728
Child = 9730
I JUST GOT FORKED 9730
Child = 9729
I JUST GOT FORKED 9729

ArcadeEdge
04-28-2012, 06:24 PM
I also tried

fork();
fork();

I got the same result as above.
3 children process with two being children of the parent and one being the child of one of the the two childrens

phantomotap
04-28-2012, 07:34 PM
O_o

This behavior you are describing is exactly what you've told the source to do.

Walk through your code, manually with text, and watch what is going to happen.

I'm not talking about `printf' lines. That is not sufficient. That will always just be the result of what you've coded.

You need to write it down so that you can see what is really happening.

Soma

ArcadeEdge
04-28-2012, 07:54 PM
Thanks for the reply.
I've been using ps -eaf in the terminal to view the processes and after looking at things a little more closely, I see what I'm doing now. Though, there is still one child process still hanging out there that I'm not really using but I guess it doesn't really matter. Since I can't seem to find away to ONLY have 3 child process from the parent.

I have another question, how can I "talk" to different terminals that are open through the different processes. For example, i have processes a, b, and c. I have terminals 1, 2, and 3 open. How can I only let a talk to 1, b talk to 2, and c talk to 3?

Right now, I am first opening the terminals, then I fork. And no I'm trying to associate the processes (via pid) to the different terminals.

phantomotap
04-28-2012, 08:03 PM
Since I can't seem to find away to ONLY have 3 child process from the parent.

And did you do what I told you do? No. You did not. You tried to look at the results. That can only tell you that you've done something wrong. You already know that. Look at the code. If you walk through the code you can see why you getting a forked process from one of the children.

Soma

ArcadeEdge
04-28-2012, 08:40 PM
Sorry.

Okay, I got rid of the for loop and now have



spawn = fork();
if(spawn > 0) spawn = fork();
if(spawn > 0) spawn = fork();