Reputation: 1413
I've got this program
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x =1;
int* y = malloc(sizeof(int));
*y = 2;
if (fork()==0)
x++;
if (fork()==0)
(*y)++;
printf("%d", (x+*y));
}
Here's the output 3445. This is what I know so far, fork() creates a new child process. 0 is returned by fork() if it's the child process and PID if it's the parent process. So once you call fork(), it becomes the parent and fork()==0 is true only on the child process and not the parent. Can anyone give me more insight to what's actually happening so that I get that output?
Upvotes: 1
Views: 202
Reputation: 3397
fork() returns -1 on error, so you have to check it too. So it is better to do something like:
int pid;
pid = fork();
if (pid == 0)
{
//child process code goes here
}
if (pid > 0)
{
//parent process code goes here
}
Note that both processes you have after the first fork() then execute fork() one more time, so you end up with 4 processes.
And, of course, the order of their execution is undefined, so you will get 3, 5 and couple of 4 in different combinations every time you run this.
Also, beware that some printf(...) and fork() combinations can lead to weird output if you don't call flush(...) before fork().
And finally, you've forget to free(y) at the end, so you leak 4*sizeof(int) bytes every time you run this program.
Upvotes: 0
Reputation: 15121
Draw a graph show child-parent relationship and stats of them are vary helpful, here is one possible form (C for child, P for parent):
fork()
C (x == 2, *y == 2)
fork()
C (x == 2, *y == 3) ==> print 5
P (x == 2, *y == 2) ==> print 4
P (x == 1, *y == 2)
fork()
C (x == 1, *y == 3) ==> print 4
P (x == 1, *y == 2) ==> print 3
So something combination of 5, 3, 4, 4 will be printed, the exact combination depends on the order of these printf()
be called, could be different from run to run.
Upvotes: 2