3

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?

unwind
  • 391,730
  • 64
  • 469
  • 606
RandomMath
  • 675
  • 15
  • 33

3 Answers3

6

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;
}
chepner
  • 497,756
  • 71
  • 530
  • 681
  • So if I wanted i=5 to print when the parent executes, how exactly could I do that without adding the statement i=5 in the parent? In short, is there a way to share variables between child and parent? – RandomMath May 20 '16 at 12:51
  • You need to pass the value to/from the child using some IPC (Inter-Process Communication) mechanism (file, pipe, socket, shared memory, ...) – AhmadWabbi May 20 '16 at 12:52
  • Some similar topic you have [here](http://stackoverflow.com/questions/10684499/sharing-same-variable-between-more-than-one-independent-programs-in-linux). Yet you have to read about Inter Process Communication (IPC). – Marcin Kajzler May 20 '16 at 12:54
4

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[]) {
    ...
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
1

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.

Sean
  • 60,939
  • 11
  • 97
  • 136