Under which circumstances a child process creates another child process using fork?
Hello,
Consider the following code: Code:
int main() Parent: chid_pid=4356 i=0 parent's pid=4355 This is child 4356 i=0 This is child 4357 i=1 This is child 4358 i=1 Parent: chid_pid=4357 i=1 parent's pid=4355 Parent: chid_pid=4358 i=1 parent's pid=4356 As I can observe instead of two children(as I expect) processes there are three. This is because child process 4356 creates its own child. Under which circumstances this happens? Why all the messages of the type "This is child X i=Y" are concentrated one under another? How exactly fork works? Is affected by the fact that I have a dual-core processor? Thanks in advance |
Quote:
Quote:
Quote:
You did not make continuing through the loop until i is 2 depend on that return value. (see alternate code below) Quote:
Quote:
Quote:
If you wanted just the two child processes you say you expected, notice where I added break to your code in the version below. That means the child does not stay in the loop so it does not create its own child. Code:
int main() |
Thank you for you answer.
Quote:
|
Quote:
Everything except the return value of fork() is duplicated Are you ignoring the fact that the variable i in your program is part of that "everything"? Or are you ignoring the way the value of i affects the subsequent behavior? As you coded the program, when you create a child in which i is 0, each of the child and the parent will create another child (and in both those children, i will be 1). When you create a child in which i is 1, neither the parent nor the child will create another child. As you coded it, whether a process goes on to create a child does not depend on whether that process is itself the original or a child. It depends only on the value of i. |
All times are GMT -5. The time now is 06:48 AM. |