Search code examples
c++coperating-systemprogram-entry-point

What do we mean when we say that control of the operating system is passed on to the main() function while execution of a program?


Let's assume that we are trying to run an arbitrary program -

int main()
{
statement 1;
statement 2;
statement 3;
}

Then it's often said that while execution of the program , the control of the OS is passed on to the main() function and after execution of all the statements inside the main function, the control is again passed back to OS.

What do we mean by control ? and if control is really passed from the OS to the program then how come multiple programs run at the same time ??


Solution

  • What you are describing is largely the function of the linker. The linker has to identify the starting address to be executed in the program.

    Some programming languages have explicit PROGRAM identifiers (e.g. Pascal, FORTRAN) to identify the starting point of the program. C uses the function name "main" to identify y the starting point.

    In some implementations the C library provides a starting point that is a wrapper around main.

    The procedure here is system-specific so I am going to be general. I assume that the process has been created. Now you are executing a system service to "run" your program. That system service invokes the the system program. The loader reads the instructions in the executable file to set up the process address space.

    Now your program is ready to run. The "run" system service branches (usually a call) to the starting address specified in the executable file. For your C program that will be either main or a wrapper around main.

    Thus your "run" system service had called your program/main/or a wrapper just like it is a function.

    When your "main" finished it returns to the caller just like any other function: the "run" system service. On some systems the system service causes the process to terminate when it resumes after a call to start function. In other systems, the system service exits and the command interpreter resumes.

    What do we mean by control ?

    Control just means invoking the instruction stream your application. Your program is being called as a function from the "run" system service.

    Calling a function means giving the function "control."

    "Run" system service calls Main that calls any other functions that return to Main when finished that returns to the "Run" system service.

    if control is really passed from the OS to the program then how come multiple programs run at the same time ??

    For that we are getting beyond the scope of the original question. This is where terminology causes a problem. Each program runs in the a separate PROCESS. The operating system manages processes. The transfer of control here is really the transfer of control of the process; not control of the system.