Python| os._exit() 方法
Python中的OS 模块提供了与操作系统交互的功能。操作系统属于 Python 的标准实用程序模块。该模块提供了一种使用操作系统相关功能的可移植方式。
Python中的os._exit()
方法用于以指定状态退出进程,而无需调用清理处理程序、刷新 stdio 缓冲区等。
注意:该方法通常在 os.fork() 系统调用后的子进程中使用。退出进程的标准方法是sys.exit(n)
方法。
Syntax: os._exit(status)
Parameter:
status: An integer value or above defined values representing the exit status.
Return type: This method does not return any value in the calling process.
代码:使用os._exit()
方法
# Python program to explain os._exit() method
# importing os module
import os
# Create a child process
# using os.fork() method
pid = os.fork()
# pid greater than 0
# indicates the parent process
if pid > 0:
print("\nIn parent process")
# Wait for the completion
# of child process and
# get its pid and
# exit status indication using
# os.wait() method
info = os.waitpid(pid, 0)
# os.waitpid() method returns a tuple
# first attribute represents child's pid
# while second one represents
# exit status indication
# Get the Exit code
# used by the child process
# in os._exit() method
# firstly check if
# os.WIFEXITED() is True or not
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..")
# Exit with status os.EX_OK
# using os._exit() method
# The value of os.EX_OK is 0
os._exit(os.EX_OK)
输出:
In child process
Process ID: 15240
Hello! Geeks
Child exiting..
In parent process
Child's exit code: 0
参考资料: https://docs。 Python.org/3/library/os.html#os._exit