Python os.WIFEXITED() - 使用exit(2)系统调用检查进程是否退出

Python os.WIFEXITED()方法

Python中的os.WIFEXITED()方法用于使用exit(2)系统调用检查进程是否退出。此方法以os.system(),os.wait()或os.waitpid()方法返回的进程状态码作为参数,如果进程使用exit(2)系统调用退出则返回True,否则返回False。

os.WIFEXITED 语法

os.WIFEXITED(status) 

os.WIFEXITED(status) 参数

status:该参数接受进程状态码(一个整数值),由os.system(),os.wait()或os.waitpid()方法返回。

返回类型:如果进程使用exit(2)系统调用退出,该方法返回True,否则返回False。

os.WIFEXITED(status) 示例1

os.WIFEXITED()方法的使用

# Python program to explain os.WIFEXITED() 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:
  
    # Create one more child
    pid2 = os.fork()
      
    if pid2 > 0:
          
        print("\nIn parent process")
        # Wait for the completion 
        # of first child process and    
        # get its pid and 
        # exit status indication using
        # os.waitpid() method
        info1 = os.waitpid(pid, 0)
  
          
        # Wait for the completion 
        # of second child process and    
        # get its pid and 
        # exit status indication using
        # os.waitpid() method
        info2 = os.waitpid(pid2, 0)
  
          
        # os.waitpid() method returns a tuple
        # first attribute represents child's pid
        # while second one represents
        # exit status indication
  
        # Check if the first child 
        # exited using exit(2) system call
        # using os.WIFEXITED() method
        if os.WIFEXITED(info1[1]) :
            print("First child exited using exit(2) system call.")
        else :
            print("First child does not exited using \
exit(2) system call.") 
          
      
        # Check if the second child 
        # exited using exit(2) system call
        # using os.WIFEXITED() method
        if os.WIFEXITED(info2[1]) :
            print("Second child exited using exit(2) system call.")
        else :
            print("Second child does not exited using \
exit(2) system call.") 
          
      
           
    else :
        print("\nIn second child process")
        print("Process ID:", os.getpid())
        print("Hey ! there")
        print("Second child aborted")
  
        # os.abort() method will
        # generate a SIGABRT signal
        # to the current process.
        os.abort()    
  
else :
    print("In first child process")
    print("Process ID:", os.getpid())
    print("Hello ! Geeks")
    print("First child exiting..")
      
    # Exit using exit(2) system call        
    os._exit(5)

输出:

In first child process
Process ID: 11614
Hello! Geeks
First child exiting..

In second child process
Process ID: 11615
Hey! there
Second child aborted

In parent process
First child exited using exit(2) system call.
Second child does not exited using exit(2) system call.

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程