Distributions
› Ubuntu
› Fedora
› CentOS
中文资源站
› 网易开源镜像站
cosmain
V2EX  ›  Linux

一个关于僵死进程处理的问题

  •  1
     
  •   cosmain · Dec 11, 2024 · 3129 views
    This topic created in 693 days ago, the information mentioned may be changed or developed.

    比如一个脚本 generator.sh

    #!/bin/bash
    
    echo "1.1.1.1"
    echo "1.0.0.1"
    
    sleep 3600
    

    再执行下面命令

    ./generator.sh | xargs -n 1 -d'\n' -P 10 -I THE_IP ping THE_IP -c 1 > /dev/null &
    

    这时候出现的情况就是,ping 都会成为僵尸进程,怎么修改脚本避免出现僵尸进程?

    Supplement 1  ·  Dec 16, 2024

    发现其实是 xargs 是单线程的,如果“|”管道的前段 sleep 没有写入信息和结束,xargs 就一直 block 在读这个系统调用,无暇执行 wait

    如果前面改成

    #!/bin/bash
    while true
    do
    echo "1.1.1.1"
    sleep 2
    done
    

    你就会发现每次循环,后面的 xargs 都会把上一轮的 ping 的僵尸进程 wait 掉。

    9 replies  •  2024-12-16 14:42:09 +08:00
    zwzwzwzwzxt
    zwzwzwzwzxt
    Dec 11, 2024
    1
    用 sh -c 包一层。

    ```
    ./generator.sh | xargs -n 1 -d'\n' -P 10 -I THE_IP sh -c 'ping THE_IP -c 1' > /dev/null &
    ```
    2owe
    2owe
    Dec 11, 2024
    2
    double fork
    gesse
    gesse
    Dec 11, 2024
    3
    按理说,xargs 应该会妥善处理 zombie 的问题的。
    ho121
    ho121
    Dec 11, 2024 via Android
    4
    把 sleep 去掉
    cosmain
    cosmain
    OP
    Dec 12, 2024
    5
    @ho121
    去掉就不是本来的意思了。
    ho121
    ho121
    Dec 12, 2024
    6
    @cosmain sleep 的存在,造成 shell 没有及时退出,进而造成 xargs 不及时退出,进而造成 xargs 没有及时回收子进程。
    cosmain
    cosmain
    OP
    Dec 12, 2024
    7
    @ho121
    僵尸进程的形成,并不是因为父进程没有退出。
    tomychen
    tomychen
    Dec 16, 2024
    8
    trap 'wait' SIGCHLD 这样应该能解了吧?
    cosmain
    cosmain
    OP
    Dec 16, 2024
    9
    @tomychen
    @ho121

    发现其实是 xargs 是单线程的,如果“|”管道的前段 sleep 没有写入信息和结束,xargs 就一直 block 在读这个系统调用,无暇执行 wait

    如果前面改成
    ```
    #!/bin/bash
    while true
    do
    echo "1.1.1.1"
    sleep 2
    done
    ```

    你就会发现每次循环,后面的 xargs 都会把上一轮的 ping 的僵尸进程 wait 掉。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   1774 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 49ms · UTC 17:22 · PVG 01:22 · LAX 09:22 · JFK 12:22
    ♥ Do have faith in what you're doing.