How multiples processes are stored in the main memory , i understand every process will be divided into the equal size pages and will be stored in the frames of main memory. if whole main memory is divided into the pages then how are stack area, heap area, code section given to the process?
my understanding is there is common stack area and heap area.
next question is :- when a method executes it is allocated in the stack area and a activation record is pushed into the stack.
I am also considering here contex switching. eg:
---------------
| process: p1 |
---------------
fun(int a)
{
if (a=0)
return 0;
fun(a--);
}
main()
{
fun(5);
}
---------------
| process: p2 |
---------------
NoFun(int a)
{
if (a=0);
return 0;
NoFun(a--);
}
main()
{
fun(3)
}
now processes p1 and p2 will be loaded into the main memory , now assume p1 started its execution so its first method main will be called and its activation records will be pushed into the stack now main calls fun() method and it started executing and after sometime this process gets preempted and context switch takes place (stack pointer of p1 will save the address of p1.fun(3) ) . so calls will look something like this.:-
p1.main() -> p1.fun(5) -> p1.fun(4) -> p1.fun(3)
so main is in the bottom of stack and fun(3) is in the top of the stack , now p2 gets chance for the execution so, main method of process p2 will get executed and will be pushed on the top of the stack i.e on the top of activation record of fun(3). so now it will look like this
p1.main() -> p1.fun(5) -> p1.fun(4) -> p1.fun(3) -> p2.main()
its time for p2 to get preempted, P1 again gets CPU and starts execution now p1 resumes back its context and go to the address of stack pointer and starts execution of remaining code.
so after execution of p1 , stack will look like this:-
p1.main() -> p1.fun(5) -> p1.fun(4) -> p1.fun(3) -> p2.main() ->p1.fun(2) ->fun(1)-> fun(0)
now p1 will start popping records:-
p1.fun(0) is popped out . p1.main() -> p1.fun(5) -> p1.fun(4) -> p1.fun(3) -> p2.main() ->p1.fun(2) ->fun(1)
p1.fun(1) is popped out . p1.main() -> p1.fun(5) -> p1.fun(4) -> p1.fun(3) -> p2.main() ->p1.fun(2)
p1.fun(2) is popped out . p1.main() -> p1.fun(5) -> p1.fun(4) -> p1.fun(3) -> p2.main()
now p1 is in the CPU and it wont be able to execute it beacause stack top is of process 2.
I know my understanding is wrong, please correct me and give some refrences.