I'm really new to C programming, although I have done quite a bit of other types of programming.
I was wondering if someone could explain to me why this program outputs 10.
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
#include <stdlib.h>
int value = 10;
int main()
{
pid_t pid;
pid = fork();
if(pid == 0){
value += 10;
}
else if(pid > 0){
wait(NULL);
printf("parent: value = %d\n", value); //Line A
exit(0);
}
}
I know the output is "parent: value = 10". Anyone know why?
Thanks!
fork
creates two processes (the "parent" and the "child"). Each process has a different value of pid in your example. The child process has a pid of 0. The parent process has a pid of the child's operating system pid (assigned by the OS.)
In your example, each process has it's own value
in its memory. They do not share memory (like you think they should by your question.) If you change one process (the first part of the if) it will not be reflected in the second process (the second part of the if.)
Edit: Explained the value of pid.
About fork() :
So in you case it bound to return a number greater than 0 & thus the value will remain 10 & will be printed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With