Skip to content
Advertisement

Counter increase in child & parent with fork()

I’ve a problem with this little program:

    int main() {

  pid_t process;
  int count= 0;

  switch(process= fork()) {

    case -1:
      printf("Fork error!nn");
      exit(1);
    break;

    case 0: //child
      printf("Process CHILD: PID= %d, Value= %d n", getpid(), process);
      printf("Coounter NOT increased: %dn", count);
      printf("Increase counter...n");
      sleep(2);
      count= count + 2;
      printf("Counter increased: %dnn", count);
      exit(0);
    break;

    default: //parent
      wait(0);
      printf("Process PARENT: PID= %d, Value= %dn", getpid(), process);
      printf("Counter value: %dnn", count);
    break;
  }
  return 0;
}

I increase the counter in the child but in the parent the counter not increase… why?

Thank you everyone

Advertisement

Answer

That’s because after fork, parent process and child process are different processes, and they each have their own copy of the variable count.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement