Last active
March 14, 2021 13:53
-
-
Save itsrobli/e8ea761e1014a6ac1bb1d92ec87ab826 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How is X different but the address of X is the same?