xzpjerry731
V2EX  ›  问与答

PY 在 Windows 下 Fork 之后在子进程执行一些操作要怎么做?

  •  
  •   xzpjerry731 · Oct 15, 2020 · 1514 views
    This topic created in 2049 days ago, the information mentioned may be changed or developed.

    下面这段代码在 Unix 平台可以输出

    (<function hook at 0x7fb4700730e0>,)
    func
    

    但是在 Windows 上就只打印 func 了,搜了一圈下来没有看到解决方法,故来求助。

    import multiprocessing.util
    
    
    def hook(*args):
        print (args)
    
    
    def func():
        print ('func')
    
    
    
    multiprocessing.util.register_after_fork(hook, hook)
    p = multiprocessing.Process(target=func)
    p.start()
    
    2 replies    2020-10-15 13:29:38 +08:00
    iConnect
        1
    iConnect  
       Oct 15, 2020 via Android
    Windows 没有这个机制,所以和 Linux 表现出差异。
    xzpjerry731
        2
    xzpjerry731  
    OP
       Oct 15, 2020
    我试了下,这样就可以了

    ···
    import multiprocessing.util


    def hook(*args):
    print (args)


    def func():
    print ('func')

    multiprocessing.util.register_after_fork(hook, hook)
    if __name__ == '__main__':
    p = multiprocessing.Process(target=func)
    p.start()
    ···
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2982 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 39ms · UTC 14:57 · PVG 22:57 · LAX 07:57 · JFK 10:57
    ♥ Do have faith in what you're doing.