V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
smallgoogle
V2EX  ›  Python

Linux 下 multiprocessing 的结束子进程问题

  •  
  •   smallgoogle · 2019-01-04 10:11:30 +08:00 · 3552 次点击
    这是一个创建于 1932 天前的主题,其中的信息可能已经有所发展或是发生改变。
    # -*- coding:utf-8 -*-
    import time
    import multiprocessing
    
    
    
    # 主进程
    def Start(num):
        while True:
            print(">>>>>>>> 我是第 " + str(num) + " 个子线程!")
            time.sleep(20)
    
    
    if __name__ == '__main__':
            # 创建子进程让定时器多进程同步运行
            i = 0
            while i < 4:
                print("创建第 " + str(i) + " 子进程!")
                t = multiprocessing.Process(target=Start, args=(i,))
                t.start()
                i = i + 1
                time.sleep(5)  # 给个延时,避免子线程启动太快导致的错误
    

    我有一个问题就是,这样创建子进程,然后我如何在 linux 下 kill 掉主进程的 pid 之后,子进程都能结束呢?
    我百度了很多文章,都没看明白人家写的意思;
    所以看看大神是否能解答一下,我大概在什么位置需要加个什么东西来处理?

    第 1 条附言  ·  2019-01-04 12:26:18 +08:00

    如果crontab.py这个是由A.py执行os.system运行的,TTY列会变成一个?号;
    然后os.killpg(pid, signal.SIGKILL) 这句话就没法结束这个进程了;
    请问这是啥问题呢?

    15 条回复    2019-01-05 01:18:14 +08:00
    mahone3297
        1
    mahone3297  
       2019-01-04 10:18:27 +08:00
    kill 主进程,子进程的父进程,应该是直接变成 init(pid 1)
    lolizeppelin
        2
    lolizeppelin  
       2019-01-04 10:19:00 +08:00
    不要老盯着 python
    好好把 linux fork wait 信号部分学一下
    你这些问题光在 python 里是解答不了的
    www5070504
        3
    www5070504  
       2019-01-04 10:22:21 +08:00
    linux 里父进程结束 子进程不一定结束啊 信号处理都是单独的 你可以试试在父进程添加信号处理函数 接收到某个信号的时候就杀死全部子进程然后父进程自己退出 这样应该可以
    tomcat65535
        4
    tomcat65535  
       2019-01-04 10:29:28 +08:00   ❤️ 1
    https://docs.python.org/3.6/library/signal.html
    你需要一个 singal handler,

    import singal

    类似于

    def int_singnal_handler(signum, frame):
    pass # do something to end your processes

    # blah blah blah

    signal.signal(signal.SIGINT, int_signal_handler)
    julyclyde
        5
    julyclyde  
       2019-01-04 10:29:51 +08:00

    这问题简直太经典了
    “单看问题”就能得出没好好读书的结论
    smallgoogle
        6
    smallgoogle  
    OP
       2019-01-04 10:33:37 +08:00
    @julyclyde 不要酱紫。
    claymore94
        7
    claymore94  
       2019-01-04 11:02:50 +08:00
    怎么输出里又有线程?

    在 t.start() 前设置:t.daemon=True
    lolizeppelin
        8
    lolizeppelin  
       2019-01-04 11:50:16 +08:00
    比较好的做法就是

    父进程开一个管道

    子进程开一个线程去阻塞读这个管道, 一旦读到就 os._exit
    firebroo
        9
    firebroo  
       2019-01-04 11:58:35 +08:00 via Android
    4 楼√
    smallgoogle
        10
    smallgoogle  
    OP
       2019-01-04 12:21:54 +08:00
    @tomcat65535 你这个方法是可行的。可是发现一个问题。如果 TTY 是一个问号。。就是假如这个脚本是由另外一个脚本发起运行的。tty 就会变成问号。然后 os.killpg 就会报错不存在这个进程。
    ooeyunarika
        11
    ooeyunarika  
       2019-01-04 12:58:27 +08:00
    4 楼√
    fengjianxinghun
        12
    fengjianxinghun  
       2019-01-04 14:00:44 +08:00
    man fork

    * The prctl(2) PR_SET_PDEATHSIG setting is reset so that the child does not receive a signal when its parent terminates.
    tomcat65535
        13
    tomcat65535  
       2019-01-04 14:10:23 +08:00
    @smallgoogle
    845 是 pid 啊
    os.killpg(os.getpgid(p.pid), signal.SIGKILL)
    =========================
    os.killpg(pgid, sig)
    Send the signal sig to the process group pgid.
    --------------------------------
    os.kill(pid, sig)
    Send signal sig to the process pid. Constants for the specific signals available on the host platform are defined in the signal module.
    fanhaipeng0403
        14
    fanhaipeng0403  
       2019-01-05 01:17:40 +08:00
    t.daeman =true
    老大做完,小弟就不做了

    t.join()
    老大等小弟做完继续在做


    class CountdownTask:
    def __init__(self):
    self._running = True

    def terminate(self):
    self._running = False

    def run(self, n):
    while self._running and n > 0:
    print('T-minus', n)
    n -= 1
    time.sleep(5)

    c = CountdownTask()
    t = multiprocessing.Process(target=c.run, args=(10,))
    t.start()
    c.terminate() # Signal termination
    t.join() # Wait for actual termination (if needed)
    老大给小弟给信号



    不知道理解的对不对、、、
    fanhaipeng0403
        15
    fanhaipeng0403  
       2019-01-05 01:18:14 +08:00
    ```
    class CountdownTask:
    def __init__(self):
    self._running = True

    def terminate(self):
    self._running = False

    def run(self, n):
    while self._running and n > 0:
    print('T-minus', n)
    n -= 1
    time.sleep(5)

    c = CountdownTask()
    t = Thread(target=c.run, args=(10,))
    t.start()
    c.terminate() # Signal termination
    t.join() # Wait for actual termination (if needed)
    ```
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2856 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 13:41 · PVG 21:41 · LAX 06:41 · JFK 09:41
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.