fork() and changing local variables?

2019-07-14 05:36发布

问题:

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?

回答1:

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;
}


回答2:

Processes are not threads! When you fork, you create a full cloned process, with independant memory allocation that simply contains same values (except for the result of the fork call) at the time of the fork.

If you want a child to update some data in the parent process, you will need to use a thread. A thread shares all static and dynamic allocated memory with its parent, and simply has independant automatic variables. But even there, you should use static allocation for i variable:

int i = 0;
int main(int argc, char *argv[]) {
    ...


回答3:

When you fork the child process gets a copy of the address space of the parent address space, they don't share it, so when the child changed i the parent won't see it.

This copying of the address space it typically done using copy on write to avoid allocating memory that will never change.



标签: c process fork