开发者社区> 问答> 正文

杀死一个子进程。用CTRL + c打开子进程

如果我在终端中以用户身份键入此命令,例如root,一个用户bob:

su - bob -c "cd /home ; ping www.google.com" 持续ping直到我按下CTRL+c。我正在尝试模仿类似的行为。我的安装脚本会先运行,然后才能安装pexpect和其他东西。由于导致ping在子进程的子进程中运行su - bob。这意味着Popen.kill()不起作用。我已经进行了一些研究,并在SO上找到了一些与PID分组然后杀死该组的答案。

问题:我想了解为什么communicate不发送CTRL+c和杀死我期望的子进程,表明我不了解一些基本知识。

import time
import subprocess

user = 'bob'    
cmd_list = ['su', '-', user, '-c','cd /home/ ; ping www.google.com ; exit']

p = subprocess.Popen(
    cmd_list,
    stdin=subprocess.PIPE,
)
print("Wait 2s...")
time.sleep(2)
print("2s passed.")

try:
    # Send CTRL+c to kill the child process from su -
    p.communicate(input='\0x03', timeout=3)
    print("CTRL+c killed the process")
except subprocess.TimeoutExpired:
    print('Timeout occured')
p.kill()

展开
收起
祖安文状元 2020-01-06 16:24:22 363 0
1 条回答
写回答
取消 提交回答
  • .communicate使用stdin,您需要使用发送信号send_signal。

    尝试这个:

    import time
    import subprocess
    import signal
    
    user = 'bob'
    cmd_list = ['su', '-', user, '-c','cd /home/ ; ping www.google.com ; exit']
    
    p = subprocess.Popen(
        cmd_list,
        stdin=subprocess.PIPE,
    )
    print("Wait 2s...")
    time.sleep(2)
    print("2s passed.")
    
    try:
        # Send CTRL+c to kill the child process from su -
        p.send_signal(signal.SIGINT)
        print("CTRL+c killed the process")
    except subprocess.TimeoutExpired:
        print('Timeout occured')
    p.kill()
    
    2020-01-06 16:24:31
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载