// CS 450: Process example 3: Address space of child processes // version 2014-01-21 7:13 PM // #include #include // fork #include // exit #include // wait // Child will get duplicate of parent's address // space, so its global variable will be at the // same location, but in its own space, not the // parent's // int glovar = 1; int main(int argc, char *argv[]) { pid_t pid = fork(); // Parent prints global var, // waits for child to finish, // then reprints global var // if (pid > 0) { fprintf(stderr, "Parent: &glovar: %p, glovar: %d\n", &glovar, glovar ); fprintf(stderr, "Wait for child with pid %d\n", pid); wait(NULL); fprintf(stderr, "Parent: glovar: %d\n", glovar); return pid; } // Child changes global variable // then returns // else if (pid == 0) { glovar = 1234; fprintf(stderr, "Child: &glovar: %p, glovar: %d\n", &glovar, glovar ); exit(0); } // Complain if fork failed // else if (pid == -1) { fprintf(stderr, "Fork failed\n"); exit(1); } } // Sample output // // Parent: &glovar: 0x10b681068, glovar: 1 // Wait for child with pid 2457 // Child: &glovar: 0x10b681068, glovar: 1234 // Parent: glovar: 1