os._exit(n) in Python
The os._exit() method in Python is used to exit the process with specified status without calling cleanup handlers, flushing stdio buffers, etc.
Note: This method is normally used in the child process after os.fork() system call. The standard way to exit the process is sys.exit(n) method.
Example : In this example the below Python code creates a parent-child process relationship using os.fork()
. The parent process waits for the child process to finish and retrieves its exit code, while the child process prints a message and exits with a status code of success.
Python3
import os pid = os.fork() if pid > 0 : print ( "\nIn parent process" ) info = os.waitpid(pid, 0 ) if os.WIFEXITED(info[ 1 ]) : code = os.WEXITSTATUS(info[ 1 ]) print ( "Child's exit code:" , code) else : print ( "In child process" ) print ( "Process ID:" , os.getpid()) print ( "Hello ! Geeks" ) print ( "Child exiting.." ) os._exit(os.EX_OK) |
Output:
In child process
Process ID: 25491
Hello ! Geeks
Child exiting..
In parent process
Child's exit code: 0
Conclusion
Among the above four exit functions, sys.exit() is preferred mostly because the exit() and quit() functions cannot be used in production code while os._exit() is for special cases only when the immediate exit is required.
Python exit commands: quit(), exit(), sys.exit() and os._exit()
The functions quit(), exit(), sys.exit(), and os._exit() have almost the same functionality as they raise the SystemExit exception by which the Python interpreter exits and no stack traceback is printed. We can catch the exception to intercept early exits and perform cleanup activities; if uncaught, the interpreter exits as usual. In this article, we will see how to exit from the Python program.