What is difference between sys.exit(0) and os._exit(0)
Asked Answered
L

3

95

Please help me in clarifying the concept of these two python statements in terms of difference in functionality:

  1. sys.exit(0)

  2. os._exit(0)

Leake answered 6/3, 2012 at 20:29 Comment(0)
G
92

According to the documentation:

os._exit():

Exit the process with status n, without calling cleanup handlers, flushing stdio buffers, etc.

Note The standard way to exit is sys.exit(n). _exit() should normally only be used in the child process after a fork().

Geniculate answered 6/3, 2012 at 20:32 Comment(1)
Could someone expand on, "should normally only be used in the child process after a fork()"? ThanksJacquelinejacquelyn
W
52

os._exit calls the C function _exit() which does an immediate program termination. Note the statement "can never return".

sys.exit() is identical to raise SystemExit(). It raises a Python exception which may be caught by the caller.

Original post: http://bytes.com/topic/python/answers/156121-os-_exit-vs-sys-exit

Willtrude answered 6/3, 2012 at 20:33 Comment(1)
What is the disadvantage of having immediate program termination?Broadax
A
9

Excerpt from the book "The linux Programming Interface":

Programs generally don’t call _exit() directly, but instead call the exit() library function, which performs various actions before calling _exit().

  • Exit handlers (functions registered with at_exit() and on_exit()) are called, in reverse order of their registration
  • The stdio stream buffers are flushed.
  • The _exit() system call is invoked, using the value supplied in status.

Could someone expand on why _exit() should normally only be used in the child process after a fork()?

Instead of calling exit(), the child can call _exit(), so that it doesn’t flush stdio buffers. This technique exemplifies a more general principle: in an application that creates child processes, typically only one of the processes (most often the parent) should terminate via exit(), while the other processes should terminate via _exit(). This ensures that only one process calls exit handlers and flushes stdio buffers, which is usually desirable

Angloirish answered 5/7, 2022 at 13:34 Comment(2)
"This ensures that only one process calls exit handlers and flushes stdio buffers, which is usually desirable" Why is that desirable?Underdrawers
Doesn't each program have its own stdio buffer? Why would not flushing the stdio buffers of the child processes be a good thing?Underdrawers

© 2022 - 2024 — McMap. All rights reserved.