Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fork() and changing local variables?

Tags:

c

fork

process

I am trying to understand the fork() concept and there's is one thing I can't seem to understand.

In the following code - why does the parent still print i=0 even when child process changes it to 5?

The wait(NULL) blocks parent process until child finishes first.

int main(int argc, char *argv[]) {
  int i = 0;
  if (fork() == 0) {
    i = 5;
  } else {
    wait(NULL);
    printf("i = %d\n", i);
  }
  return 0;
}

Can somebody explain why my assumption is incorrect?

like image 685
RandomMath Avatar asked Apr 29 '26 01:04

RandomMath


1 Answers

Variables are not shared between processes. After the call to fork, there are two completely separate processes. fork returns 0 in the child, where the local variable is set to 5. In the parent, where fork returns the process ID of the child, the value of i is not changed; it still has the value 0 set before fork was called. It's the same behavior as if you had two programs run separately:

int main(int args, char *argv[]) {
    int i=0;
    printf("i = %d\n", i);
    return 0;
}

and

int main(int argc, char *argv[]) {
  int i = 0;
  i = 5;
  return 0;
}
like image 87
chepner Avatar answered May 01 '26 22:05

chepner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!