Python| os.kill() 方法
Python中的OS 模块提供了与操作系统交互的功能。操作系统属于 Python 的标准实用程序模块。该模块提供了一种使用操作系统相关功能的可移植方式。
Python中的os.kill()方法用于向具有指定进程 ID 的进程发送指定信号。主机平台上可用的特定信号的常量在信号模块中定义。
Syntax: os.kill(pid, sig)
Parameters:
pid: An integer value representing process id to which signal is to be sent.
sig An integer representing signal number or the signal constant available on the host platform defined in the signal module to be sent.
Return type: This method does not return any value.
代码:使用os.kill()方法
Python3
# Python program to explain os.kill() method
# importing os and signal module
import os, signal
# Create a child process
# using os.fork() method
pid = os.fork()
# pid greater than 0
# indicates the parent process
if pid :
print("\nIn parent process")
# send signal 'SIGSTOP'
# to the child process
# using os.kill() method
# 'SIGSTOP' signal will
# cause the process to stop
os.kill(pid, signal.SIGSTOP)
print("Signal sent, child stopped.")
info = os.waitpid(pid, os.WSTOPPED)
# waitpid() method returns a
# tuple whose first attribute
# represents child's pid
# and second attribute
# representing child's status indication
# os.WSTOPSIG() returns the signal number
# which caused the process to stop
stopSignal = os.WSTOPSIG(info[1])
print("Child stopped due to signal no:", stopSignal)
print("Signal name:", signal.Signals(stopSignal).name)
# send signal 'SIGCONT'
# to the child process
# using os.kill() method
# 'SIGCONT' signal will
# cause the process to continue
os.kill(pid, signal.SIGCONT)
print("\nSignal sent, child continued.")
else :
print("\nIn child process")
print("Process ID:", os.getpid())
print("Hello ! Geeks")
print("Exiting")
输出:
In child process
In parent process
Signal sent, child stopped.
Child stopped due to signal no: 19
Signal name: SIGSTOP
Signal sent, child continued.
Process ID: 5166
Hello! Geeks
Exiting
参考资料: https://docs。 Python.org/3/library/os.html#os.kill