Skip to content

Instantly share code, notes, and snippets.

@itsrobli
Last active March 14, 2021 13:53
Show Gist options
  • Save itsrobli/e8ea761e1014a6ac1bb1d92ec87ab826 to your computer and use it in GitHub Desktop.
Save itsrobli/e8ea761e1014a6ac1bb1d92ec87ab826 to your computer and use it in GitHub Desktop.
//
// Created by Robert Li on 14/3/21.
//
/*
* Write a program that calls fork(). Before calling fork(), have the main process access a variable (e.g., x) and
* set its value to something (e.g., 100). What value is the variable in the child process? What happens to the
* variable when both the child and parent change the value of x?
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main(int argc, char *argv[])
{
int x = 9;
printf("Address of X initially: %p\n", &x);
printf("hello world (pid:%d), (value of X: %d)\n", (int) getpid(), x);
int rc = fork();
if (rc < 0) {
// fork failed; exit
fprintf(stderr, "fork failed\n");
exit(1);
} else if (rc == 0) {
// child (new process)
printf("hello, I am child (pid:%d) (value of X: %d)\n", (int) getpid(), x);
printf("Address of X in Child: %p\n", &x);
x = 10;
printf("In Child X is now %d\n", x);
printf("Address of X in Child is now: %p\n", &x);
sleep(1);
} else {
printf("Address of X in Parent after fork: %p\n", &x);
// parent goes down this path (original process)
int wc = wait(NULL);
printf("hello, I am parent of %d (wc:%d) (pid:%d) (value of X: %d)\n",
rc, wc, (int) getpid(), x);
}
return 0;
}
@itsrobli
Copy link
Author

/usr/bin/make -f /Users/robertli/Documents/Workspace_Coding/ostep/ostep-homework/cpu-api/Makefile run-fork
gcc -o fork fork.c -Wall
./fork
Address of X initially: 0x7ffee05f0abc
hello world (pid:74633), (value of X: 9)
Address of X in Parent after fork: 0x7ffee05f0abc
hello, I am child (pid:74634) (value of X: 9)
Address of X in Child: 0x7ffee05f0abc
In Child X is now 10
Address of X in Child is now: 0x7ffee05f0abc
hello, I am parent of 74634 (wc:74634) (pid:74633) (value of X: 9)

Process finished with exit code 0

How is X different but the address of X is the same?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment