當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Python os.kill()用法及代碼示例


Python中的OS模塊提供了與操作係統進行交互的函數。操作係統屬於Python的標準實用程序模塊。該模塊提供了使用依賴於操作係統的函數的便攜式方法。

os.kill()Python中的方法用於將指定的信號發送到具有指定進程ID的進程。在信號模塊中定義了主機平台上可用的特定信號的常量。

用法: os.kill(pid, sig)

參數:
pid:一個整數值,表示要向其發送信號的進程標識。
sig一個整數,表示信號號或在要發送的信號模塊中定義的主機平台上可用的信號常數。

返回類型:此方法不返回任何值。

代碼:用於os.kill()方法

# 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 
    # represnting 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



相關用法


注:本文由純淨天空篩選整理自ihritik大神的英文原創作品 Python | os.kill() method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。