CS360 Lecture notes -- How Does a Process Terminate

  • Jian Huang
  • Directory: ~huangj/cs360/notes/Term
  • Lecture notes: http://www.cs.utk.edu/~huangj/cs360/360/notes/Term/lecture.html

    After knowing all about process control and signals, let's take a step back and try to understand how a process gets started and terminated.


    main function

    A C program starts to execute with the C start-up routine calling the main function. This happens after an exec function is called. The executable program file specifies this start-up routine as the starting address of the program, set up by the linker. This start-up routine is very simple, all it does is to take values from the kernel, like the command-line arguments and env values (can you relay back to what we talked about during lectures about stack?). After this step, main is called just like a regular function.


    Termination

    We have said that a large number of signals are really meant to kill the process, but there are better ways for a program to quit. In general, there are five of them:

       1. Normal termination
          (a) return from main, conceptually the C start-up routine calls "exit(main(argc,argv));" when main returns
          (b) calling exit
          (c) calling _exit
       2. Abnormal termination
          (a) calling abort
          (b) terminated by a signal
    

    exit and _exit

    exit is part of ANSI C, and _exit is specified by POSIX.1. So,
       #include < stdlib.h >
       void exit(int status);
    
       #include < unistd.h >
       void _exit(int status);
    

    exit performs a clean shutdown of the standard I/O library (fclose is called on all open streams, thus flushing all buffered output data). In addition, exit also calls up to 32 exit handlers that have been registered with the process with:

        #include < stdlib.h >
        int atexit(void (*func)(void));
    

    The exit handlers are called in the reverse order that they are specified. By the end, exit calls _exit.

    _exit is a direct call to the kernel to end the process. Don't use it directly in your C program, unless there is a really good reason to do so.