Search code examples
linuxprocesslinux-kernelpthreadssigkill

How linux terminate processes


I want know some details about process termination. Thanks. Does process have cancellation points like pthread? If yes, what are they? Does SIGKILL take those cancellation points into account? Does signal change process states to run signal handler? If yes, does it mean a process will never terminate itself when it never get cpu.


Solution

  • Does process have cancellation points like pthread?

    No.

    Does SIGKILL take those cancellation points into account?

    No, because there are none. When a SIGKILL is delivered to a process, it dies. If it is waiting on completion of any system calls then those waits are interrupted. No thread makes any further computational progress or performs any cleanup, but on-termination cleanup performed by the OS (closing open files, releasing memory, ...) generally still happens. SIGKILL cannot be caught, blocked, or ignored.

    Compare SIGTERM, which is a bit gentler. When a process receives a SIGTERM, which may be deferred by blocking it or prevented by ignoring it, the result depends on whether a signal handler is registered for it. If so, then any system call being executed by the thread chosen to receive the signal is interrupted, and the signal handler is called. Additional effects are program-specific. If no handler is registered then the program skips to performing a clean(-ish) termination, including calling registered exit handlers before actually terminating.

    Does signal change process states to run signal handler?

    I'm not sure what you mean by that, but no signal handlers are invoked in the SIGKILL case. More broadly, however, when signal handlers do run, such as may happen in the SIGTERM case, they are asynchronous with respect to the execution of the thread in which they run.

    If yes, does it mean a process will never terminate itself when it never get cpu.

    Terminating a process by delivering a SIGKILL to it does not require any cooperation from the process. All significant operations involved are performed by the kernel, and since it is in charge of scheduling execution resources, you cannot easily deny the kernel whatever CPU time it wants.

    Delivering a SIGTERM to a process, on the other hand, is not always successful in making it terminate. The process can block or ignore the signal, or handle it without terminating. Even if it does none of those things, its exit handlers (if any) will run before it terminates, and these can delay its actual termination indefinitely. In principle, you can prevent the termination from completing by preventing the process from being scheduled any CPU time.