Python os.waitid() - 等待一个或多个子进程完成

Python os.waitid()方法

Python中的os.waitid()方法被进程用来等待一个或多个子进程完成

os.waitid 语法

os.waitid(idtype, id, options) 

os.waitid 参数

id:一个整数值,表示要等待的子进程的进程id。

idtype: idtype和id参数指定方法等待的子方法。

返回类型:该方法返回一个表示siginfo_t结构中包含的数据的对象。

os.waitid 示例1

使用os.waitid()方法

# Python program to explain os.waitid() method 
  
# importing os module  
import os 
  
# Create a child process
# using os.fork() method 
pid = os.fork()
  
  
# a Non-zero process id (pid)
# indicates the parent process 
if pid :
      
    # Wait for the completion of
    # child process using
    # os.waitid() method
  
    # Specify idtype
    idtype = os.P_PID
  
    # Specify id
    id = pid
      
    # Specify option
    option = os.WEXITED
  
    status = os.waitid(idtype, id, option)
  
    print("\nIn parent process-")
      
    # Print status
    print("Status of child process:")
    print(status)
  
  
else :
    print("In Child process-")
    print("Process ID:", os.getpid())
    print("Hello ! Geeks")
    print("Exiting..")
     

输出:

In Child process-
Process ID: 10309
Hello! Geeks
Exiting..

In parent process-
Status of child process:
posix.waitid_result(si_pid=10309, si_uid=1000, si_signo=17, si_status=0, si_code=1)

os.waitid 示例2

使用os.waitid()方法

# Python program to explain os.waitid() method 
  
# importing os module  
import os 
  
# Create a child process
# using os.fork() method 
pid = os.fork()
  
  
# a Non-zero process id (pid)
# indicates the parent process 
if pid :
      
    # Create one more child process 
    pid2 = os.fork()
      
    if pid2 :
      
        # Wait for the completion of
        # any child processes using
        # os.waitid() method
  
        # Specify idtype
        idtype = os.P_ALL
  
        # Specify id
        # As idtype is os.P_ALL
                # method will wait for 
        # any children and specified id 
        # is ignored.             
        id = pid
  
        # Specify option
        option = os.WSTOPPED | os.WEXITED
      
        status = os.waitid(idtype, id, option)
  
        print("\nIn parent process-")
          
        # Print status
        print("Status of completed child process:")
        print(status)
  
    else :
        print("\nIn Second Child process-")
        print("Process ID:", os.getpid())
        print("Hey ! There  ")
        print("Exiting")
  
  
else :
    print("In First Child process-")
    print("Process ID:", os.getpid())
    print("Hello ! Geeks")
    print("Exiting")
     

输出:

In First Child process-
Process ID: 11524
Hello! Geeks
Exiting

In Second Child process-
Process ID: 11525
Hey! There  
Exiting

In parent process-
Status of completed child process:
posix.waitid_result(si_pid=11524, si_uid=1000, si_signo=17, si_status=0, si_code=1)

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程