nested fork () - how to count number of processes - c

I get confused with this example for Fork()
int main(){
if (fork()){
if (!fork())
fork();
}
fork();
printif("1 ");
}
I count them and it'll be 12 repeated ones (how many processes will be !!!)

Let count them:
int main(){
if (fork()){ // 1
if (!fork()) // 2
fork(); // 3
}
fork(); // 4
printif("1 ");
}
When you run the program, you have the first process which will be the ancestor of all others.
fork_1 will create a child process, the latter will have 0 as returned value. so it will continue after the if statement, then runs fork_4, hence another child is created.
printf is run twice (2) for now.
Let continue with the first process that get a non-null value, it runs fork_2 and then gets a non-null returned value. It continues after the second if statement, runs fork_4. There will be two processes (the ancestor and its child process) => another two printf.
The child process created in fork_2 will get a null returned value, so the if condition is true. It runs fork_3 which gives two processes and each one of them runs fork_4. So printf will be run four (4) times.
At the end, printf is run 8 times. So you will get eight 1 printed.

Related

Number of possible combinations of fork

int main(void) {
int id = 0;
for(int i = 1; i < 4; i++) {
if(fork() == 0) {
id = i;
} else {
printf("Process %d created child %d\n", id, i);
}
}
return 0;
}
In the code above, multiple ordering of the output (printf statements) can be generated based on how the operating system schedules processes for execution. How many different orderings are possible? You may assume that all fork and printf calls succeed.
I'm trying to help my students understand how to approach this problem, however I got a nice 0 on this question when I wrote the exam. I was hoping someone could explain how to go about it?
I haven't worked out all the combinations at the end, but this should get you going.
You start with a parent process. It will call fork() 3 times, and print
Process 0 created child 1
Process 0 created child 2
Process 0 created child 3
After its first fork there's one child process with id = 1. This process will continue the loop, so it will print
Process 1 created child 2
Process 1 created child 3
The parent process will then fork a child with id = 2. This process will also continue its loop, so it will print
Process 2 created child 3
That's all the first generation children. But child 1 also forks its own child 2, which will print
Process 2 created child 3
All the processes that are forked when i = 3 exit the loop immediately. They don't fork any more children, or print anything, so they can be ignored.
Each process prints its own messages in order, but they can be interspersed in any order between the processes. The one constraint is that a a child can't print anything before its parent prints the message saying that it created an earlier child, because the message is printed before the iteration that creates the child (I'm assuming output is line buffered). But it can print its own messages before the message that says it was created!
So the first two messages can be either:
Process 0 created child 1
Process 1 created child 2
or
Process 1 created child 2
Process 0 created child 1

How to take advantage of each process when using two fork()'s in C

So, I've been trying to understand forks, and although I understand the basics (ie. another process gets created with a copy of the original data when we use fork()), I can't really grasp actually doing things with these processes that are created.
For example: I have to write a program that will call fork() twice to create 4 processes in total. When one process is created I have to print out the pid with getpid(). After printing out four ID's, my program is supposed to print a single letter 10 times.
For example, parent 1 will print 'A', child 1 will print 'B', child 2 will print 'C' and the parent of that will print 'D'. To do this, I have to use putchar(ch); and flush the output with fflush(stdout).
This means the output will look like this:
Process created, ID: 3856
Process created, ID: 3857
Process created, ID: 3858
Process created, ID: 3859
AAAAAABBBBBBBCDCDCDCDCDCDCBBBDCDCAAAADCD
So far, I've gotten the four processes to print with this code:
int main(void) {
pid_t child1, child2;
child1 = fork();
child2 = fork();
printf("Process created. ID: %d\n", getpid());
}
But I don't know how to use wait() to have everything print out randomly, after I have printed the ids.
To get everything I need to print out to be a "random mess," what should I do? Should I call functions like this?
// in main
for(int i = 0; i < 10; ++i) {
char_parent1();
char_child1();
char_parent2();
char_child2();
}
return 0;
}
void char_parent1()
{
putchar('A');
fflush(stdout);
}
void char_child1()
{
putchar('B');
fflush(stdout);
}
// and so on for char_parent2() and char_child2()
In that case, if my professor says I have to basically print things out concurrently and randomly, then why should I be using wait()?
Each process needs to know which letter it is supposed to print. That means you have to analyze the values in child1 and child2. For example, one process has two zeros; it might print D.
Arguably, each process needs to know whether it is a parent or not. If it is not a parent, it can simply exit after printing 10 copies of its letter, each followed by a fflush(). If it is a parent, after waiting for its children to die, it should exit. This means that the original process will exit last. It could usefully output a newline after its last child has died. You might or might not print diagnostic information about dead children as you go.

Visually what happens to fork() in a For Loop

I have been trying to understand fork() behavior. This time in a for-loop. Observe the following code:
#include <stdio.h>
void main()
{
int i;
for (i=0;i<3;i++)
{
fork();
// This printf statement is for debugging purposes
// getppid(): gets the parent process-id
// getpid(): get child process-id
printf("[%d] [%d] i=%d\n", getppid(), getpid(), i);
}
printf("[%d] [%d] hi\n", getppid(), getpid());
}
Here is the output:
[6909][6936] i=0
[6909][6936] i=1
[6936][6938] i=1
[6909][6936] i=2
[6909][6936] hi
[6936][6938] i=2
[6936][6938] hi
[6938][6940] i=2
[6938][6940] hi
[1][6937] i=0
[1][6939] i=2
[1][6939] hi
[1][6937] i=1
[6937][6941] i=1
[1][6937] i=2
[1][6937] hi
[6937][6941] i=2
[6937][6941] hi
[6937][6942] i=2
[6937][6942] hi
[1][6943] i=2
[1][6943] hi
I am a very visual person, and so the only way for me to truly understand things is by diagramming. My instructor said there would be 8 hi statements. I wrote and ran the code, and indeed there were 8 hi statements. But I really didn’t understand it. So I drew the following diagram:
Diagram updated to reflect comments :)
Observations:
Parent process (main) must iterate the loop 3 times. Then printf is called
On each iteration of parent for-loop a fork() is called
After each fork() call, i is incremented, and so every child starts a for-loop from i before it is incremented
At the end of each for-loop, "hi" is printed
Here are my questions:
Is my diagram correct?
Why are there two instances of i=0 in the output?
What value of i is carried over to each child after the fork()? If the same value of i is carried over, then when does the "forking" stop?
Is it always the case that 2^n - 1 would be a way to count the number of children that are forked? So, here n=3, which means 2^3 - 1 = 8 - 1 = 7 children, which is correct?
Here's how to understand it, starting at the for loop.
Loop starts in parent, i == 0
Parent fork()s, creating child 1.
You now have two processes. Both print i=0.
Loop restarts in both processes, now i == 1.
Parent and child 1 fork(), creating children 2 and 3.
You now have four processes. All four print i=1.
Loop restarts in all four processes, now i == 2.
Parent and children 1 through 3 all fork(), creating children 4 through 7.
You now have eight processes. All eight print i=2.
Loop restarts in all eight processes, now i == 3.
Loop terminates in all eight processes, as i < 3 is no longer true.
All eight processes print hi.
All eight processes terminate.
So you get 0 printed two times, 1 printed four times, 2 printed 8 times, and hi printed 8 times.
Yes, it's correct. (see below)
No, i++ is executed after the call of fork, because that's the way the for loop works.
If all goes successfully, yes. However, remember that fork may fail.
A little explanation on the second one:
for (i = 0;i < 3; i++)
{
fork();
}
is similar to:
i = 0;
while (i < 3)
{
fork();
i++;
}
So i in the forked processes(both parent and child) is the value before increment. However, the increment is executed immediately after fork(), so in my opinion, the diagram could be treat as correct.
To answer your questions one by one:
Is my diagram correct?
Yes, essentially. It's a very nice diagram, too.
That is to say, it's correct if you interpret the i=0 etc. labels as referring to full loop iterations. What the diagram doesn't show, however, is that, after each fork(), the part of the current loop iteration after the fork() call is also executed by the forked child process.
Why are there two instances of i=0 in the output?
Because you have the printf() after the fork(), so it's executed by both the parent process and the just forked child process. If you move the printf() before the fork(), it will only be executed by the parent (since the child process doesn't exist yet).
What value of i is carried over to each child after the fork()? If the same value of i is carried over, then when does the "forking" stop?
The value of i is not changed by fork(), so the child process sees the same value as its parent.
The thing to remember about fork() is that it's called once, but it returns twice — once in the parent process, and once in the newly cloned child process.
For a simpler example, consider the following code:
printf("This will be printed once.\n");
fork();
printf("This will be printed twice.\n");
fork();
printf("This will be printed four times.\n");
fork();
printf("This will be printed eight times.\n");
The child process created by fork() is an (almost) exact clone of its parent, and so, from its own viewpoint, it "remembers" being its parent, inheriting all of the parent process's state (including all variable values, the call stack and the instruction being executed). The only immediate difference (other than system metadata such as the process ID returned by getpid()) is the return value of fork(), which will be zero in the child process but non-zero (actually, the ID of the child process) in the parent.
Is it always the case that 2^n - 1 would be a way to count the number of children that are forked? So, here n=3, which means 2^3 - 1 = 8 - 1 = 7 children, which is correct?
Every process that executes a fork() turns into two processes (except under unusual error conditions, where fork() might fail). If the parent and child keep executing the same code (i.e. they don't check the return value of fork(), or their own process ID, and branch to different code paths based on it), then each subsequent fork will double the number of processes. So, yes, after three forks, you will end up with 2³ = 8 processes in total.

Fork() command issue

While going thorough fork() command i got struck with a question .
how many no.of processes are created by the end of 12th second, if
time starts from 0th second? Process id's start from 0.
Pseudo code
while(true)
{
sleep 1second;
if( getpid() % 2 == 0 )
{
fork();
printf("Hello\n");
}
}
when i run above code on my system it is not showing output on konsole. Is no . of process at end of 12 sec is dependent on OS ?Need suggestion as i am not good in fork()
Since when do process IDs "start at 0"? Not even when the system boots; the first process has the id 1 :-)
You're only fork()ing when your own process ID is even; so if it happens to be odd then nothing will happen... which means that if you run the program several times, sometimes it will do something and sometimes it won't.
Add this after your printf:
fflush(stdout);
But you have a fundamental problem with your logic. fork() returns 0 in the child, and the child pid in the parent. You don't check, so both the parent and the child continue doing the loop, which happens again, and again, and again, forever. You need to change the loop body to this:
if(fork() == 0)
{
printf("Hello!\n");
fflush(stdout);
}

I don't understand this diagram of fork()

How we can get this process with this condition??schema of process?
int main (int argc, char **argv) {
int i;
int pid;
for (i= 0; i < 3; i++) {
pid = fork();
if (pid < 0) break;// with this condition i dont understand??
}
while (wait(NULL) != -1);
fork() splits a process in two, and returns 0 (if this process is the child), or the PID of the child (if this process is the parent), or -1 if the fork failed. So, this line:
if (pid < 0) break;
Says "exit the loop if we failed to create a child process".
The diagram is a little confusing because of the way the processes (circles) correspond to the fork() calls in the loop. The three child processes of the main process are created when i is 0, 1, and 2 respectively (see the diagram at the bottom of this post).
Since the loop continues in both the parent and the child process from the point fork was called, this is how the forks happen:
i == 0: fork is called in the original parent. There are now two processes (the top one, and the left one).
i == 1: fork is called in the two existing processes. New children are the leftmost child on the second layer from the bottom, and the middle child on the third layer from the bottom. There are now four processes
i == 2: fork is called in all existing processes. New children are all remaining nodes (the bottom node, the two rightmost nodes in the second layer from the borrom, and the rightmost node in the third layer from the bottom)
i == 3: All 8 processes exit the loop
Here is the diagram again, with numbers indicating what the value of i was in the loop when the process was created:
-1 <--- this is the parent that starts the loop
/ | \
0 1 2
/ \ |
1 2 2
|
2
To understand your diagram you must rely on the behavior of fork: it splits the process in two, creating another process identical to the first (except for the PID) in a new memory location.
If you call it in a loop that's what happen:
When i=0 the first process will be split, creating another process that will start running from exactly this point on (so will skip the first loop). Focusing on the first process, it will continue the loop, generating another process when i=1. The second process, thus, will start from i=1, so will skip the first two loops. The first process will be split last time for i=2. The last copy created, however, will start running from i=2, so it will exit the loop and will not generate anything.
The first copy created will start the loop from i=1, generating two process, while the second copy will start from i=2, generating only one copy.
You can continue this reasoning and understand the rest of the diagram.
As others pointed out, if (pid < 0) is just a check to see if there are errors and does not modify the logic of the code.
fork returns -1 if the fork call failed. it returns the pid in parent and 0 in the child. The condition you're looking at doesn't really matter to the functioning of the code; it's just saying if there's an error with fork then exit the loop. If there's no error in the fork call then the process tree in your diagram will be built.
The reason why is that the same loop will continue running in the child processes. So the children will also continue to fork based on the value of i at the time fork was called.
fork return -1 on error, and 0 or positive else, so the line if (pid < 0) break; says "if there was error, exit from the loop".
Assuming that there is not error, it's something like:
At the beginning, i=0, and you have one process. let's call it p0.
In the line fork();, p0 creates another process. let's call it p1.
In everyone of them, we have i++ (so now i is 1), and we are iterating the loop again.
p0 and p1, separately, have a fork(); command, so everyone of them creates another process. let's call the new processes p2 and p3.
Now, in every process, we have i++, that set i to be 2, and we run the loop again.
Everyone of the 4 processes we have, run the line fork();, and creates a new process. so now we have also p4,p5,p6,p7.
Every process increase its i to 3, and then, since the loop condition is now false, the loop finally ends.
Now, the 8 process arrive (separately) to the next line.
(In fact, every iteration double the number of processes, so if you change the 3 to, for example, 15, you will have 2^15 processes at the end.)

Resources