The nice part about fork()
is that each process you spawn automatically gets a copy of everything the parent has, so for example, let's say we want to pass an int myvar
to each of two child processes but I want each to have a different value from the parent process:
int main()
{
int myvar = 0;
if(fork())
myvar = 1;
else if(fork())
myvar = 2;
else
myvar = 3;
printf("I'm %d: myvar is %d
", getpid(), myvar);
return 0;
}
So doing this allows each process to have a "copy" of myvar
with it's own value.
I'm 8517: myvar is 1
I'm 8518: myvar is 2
I'm 8521: myvar is 3
If you didn't change the value, then each fork'd process would have the same value.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…