1

我如何在 Python3.3 中使用 fork() **这是我的代码:

输入:

#!/usr/bin/env python
import os

def Child_process():
    print("We are in Child_Process")
    print("My PID: %d"%os.getpid())
    print("Child_Process is exiting")

def Parent_process():
    print("-------Parent_process---------")
    wpid = os.fork()
    if wpid==0:
        print("wpid is 0 means We are in Child_process")
        print("Child :%d"%wpid)
        Child_process()
    else:
        print("Execute Parent_process")
        print("Parent_process %d"%wpid)
        Parent_process()

Parent_process()

输出:

C:\Python33\python.exe C:/Users/Iem-Prog/Desktop/Py/Fork

Traceback (most recent call last):

  File "C:/Users/Iem-Prog/Desktop/Py/Fork", line 21, in <module>
-------Parent_process---------
    Parent_process()
  File "C:/Users/Iem-Prog/Desktop/Py/Fork", line 11, in Parent_process
    wpid = os.fork()

AttributeError: 'module' object has no attribute 'fork'
4

3 回答 3

10

os.fork仅在类 Unix 系统中可用。您不能在 Windows 中使用它。

os.fork()

fork 一个子进程。在子进程中返回 0,在父进程中返回子进程 ID。如果发生错误,则会引发 OSError。

请注意,包括 FreeBSD <= 6.3、Cygwin 和 OS/2 EMX 在内的某些平台在从线程中使用 fork() 时存在已知问题。

可用性:Unix。

于 2013-10-23T16:40:04.367 回答
2

由于os.fork在您的目标上不可用,请考虑改用subprocess模块甚至 (batteries-not-included) envoy

这些创建了围绕启动孩子的方便抽象。

于 2013-10-23T18:17:47.247 回答
1

You should use the python's default multiprocessing package. It works with both Linux and Windows.

from multiprocessing import Process, Array

def split_work_receiver(import_type, process_no, i, shared_arr):
   creds= login()

    if creds is not None:
        process_submissions(browser, i, import_type, process_no, shared_arr)
    else:
        print("Failed login.")
    return

def split_work(base_path, i, connection_url, database_name):
    shared_arr = Array('i', range(0)) # Used to send data across processeses
    processes = [
        Process(target=split_work_receiver, args=("arg1", base_path, i, shared_arr)),
        Process(target=split_work_receiver, args=("arg1", base_path, i, shared_arr)),
        Process(target=split_work_receiver, args=("arg1", base_path, i, shared_arr))]

    #Run processes
    for p in processes:
        p.start()

    while True:
        sleep(600)

    #Exit the completed processes
    for p in processes:
        print('Closed process: '+ str(p))
        p.join()
于 2018-09-23T10:11:07.533 回答