[Python] SIGUSR1 signal mysteriously fails with `tar`, kills process instead of reporting...

Discussão em 'Python' iniciado por Stack, Setembro 1, 2025.

  1. Stack

    Stack Membro Participativo

    I'm executing a tar process with the subprocess module and I discovered the ability to use signals to get progress information out of it (send to stderr).

    $ tar -xpf archive.tar --totals=SIGUSR1 ./blah
    $ pkill -SIGUSR1 tar # separate terminal, session etc.


    Unfortunately, I am unable to replicate this sequence successfully in Python.

    import os
    import subprocess
    import signal
    import time
    import sys

    # Define the command to execute
    command = ["tar", "-xpf", sys.argv[2], "-C", sys.argv[1], "--totals=SIGUSR1"]

    # Start the subprocess
    print(' '.join(command))
    process = subprocess.Popen(command, preexec_fn=os.setsid, stderr=subprocess.PIPE)

    try:
    while True:
    # Ping the subprocess with SIGUSR1 signal
    # NOTWORK: process.send_signal(signal.SIGUSR1)
    # NOTWORK: os.killpg(os.getpgid(process.pid), signal.SIGUSR1)
    subprocess.Popen(["kill", "-SIGUSR1", str(process.pid)])

    print(process.stderr.readline().decode("utf-8").strip())
    # print(process.stdout.readline().decode("utf-8").strip())

    # Wait for a specified interval
    time.sleep(1.9) # Adjust the interval as needed

    except KeyboardInterrupt:
    # Handle Ctrl+C to gracefully terminate the script
    process.terminate()

    # Wait for the subprocess to complete
    process.wait()


    The only style that works is opening a kill process with Popen like a cave man.

    I noticed that after using os.kill or Popen.send_signal, the .poll() method returns -10. Seems like it dies after receiving the signal for some reason?

    Continue reading...

Compartilhe esta Página