一、使用subprocess模块

使用subprocess模块可创建子进程。

subprocess. Popen ( args , bufsize=0 , executable=None , stdin=None , stdout=None , stderr=None , preexec_fn=None , close_fds=False , shell=False , cwd=None , env=None , universal_newlines=False , startupinfo=None , creationflags=0 )

subprocess.Popen(['google-chrome',"http://www.baidu.com"])可打开chrome并显示百度网页。

subprocess.Popen.pid可显示子进程的id,但这只是打开的shell的id,如果此时使用pid.kill是无法杀掉所有子进程的。

杀掉所有子进程,代码:

import sys, os, subprocess, time, signal
p = subprocess.Popen(['google-chrome',"http://www.baidu.com"], close_fds=True, preexec_fn = os.setsid)
print p.pid
time.sleep(5)
# p.kill() #无法杀掉所有子进程,只能杀掉子shell的进程 # p.terminate() #无法杀掉所有子进程
os.killpg( p.pid,signal.SIGUSR1) time.sleep(3)

注意:

close_fds=True,此时除了文件描述符为0 , 1 and 2,其他子进程都要被杀掉。( Linux中所有的进程都是进程0的子进程。

pid=1的是init,内核完成之后启动的第一个进程,然后init根据/etc/inittab的内容再去启动其它进程。)

os.setsid(): 使独立于终端的进程(不响应sigint,sighup等),使脱离终端。

SIGUSR1: 用户自定义信号

os.killpg( p.pid,signal.SIGUSR1): 发送SIGUSR1信号到组进程p.pid

二、封装subprocess 函数

最近使用python 调用ansible命令,来监测系统相关服务。发现到达指定时间,ansible进程没有杀掉。导致服务器卡死。

后来尝试 使用os.killpg ,发现可以杀掉ansible 子进程。

完整代码如下:

#!/usr/bin/env python3
# coding: utf-8 import os
import time
import signal
import subprocess def execute_linux2(cmd, timeout=10, skip=False):
"""
执行linux命令,返回list
:param cmd: linux命令
:param timeout: 超时时间,生产环境, 特别卡, 因此要3秒
:param skip: 是否跳过超时限制
:return: list
"""
p = subprocess.Popen(cmd, stderr=subprocess.STDOUT, stdout=subprocess.PIPE,shell=True,close_fds=True,preexec_fn=os.setsid) t_beginning = time.time() # 开始时间
while True:
if p.poll() is not None:
break
seconds_passed = time.time() - t_beginning
if not skip:
if seconds_passed > timeout:
# p.terminate()
# p.kill()
# raise TimeoutError(cmd, timeout)
print('错误, 命令: {},本地执行超时!'.format(cmd))
# 当shell=True时,只有os.killpg才能kill子进程
try:
# time.sleep(1)
os.killpg(p.pid, signal.SIGUSR1)
except Exception as e:
pass
return False result = p.stdout.readlines() # 结果输出列表
return result

本文参考链接:

https://blog.csdn.net/heihuifeng/article/details/6543414

最新文章

  1. WIN32服务程序(二):卸载服务
  2. pageX,clientX,screenX,offsetX的区别
  3. MySql下载安装(Mac平台) 终端启动 XMAPP启动
  4. Oracle数据库--SQL函数
  5. CSS3的文字阴影—text-shadow
  6. Jquery 实现banner图滚动效果
  7. 【c实现,vc6调试通过】给出一字符串指针,计算出字符串指针中单词数
  8. Entity Framework 5.0
  9. gcc/g++/make 编译信息带颜色输出
  10. 使用date转换UNIX时间戳
  11. DirectX SDK版本与Visual Studio版本
  12. 【BZOJ 1002】: [FJOI2007]轮状病毒
  13. HFS 轻量化 的文件服务器
  14. sql语句循环截取字符串
  15. Unity3D游戏开发框架-资源管理类ResourceManage
  16. Android Studio项目生成Jar包
  17. docker swarm 实例
  18. Spring+Tomcat的JNDI数据源连接池简单配置
  19. unigui1404在delphi10.2.2安装
  20. 程序员们必备的10款免费jquery插件

热门文章

  1. 【洛谷P3391】文艺平衡树——Splay学习笔记(二)
  2. java学习笔记(5) 控制语句、键盘输入
  3. 修改elementUI源码新增组件/修改组件
  4. HDU-5215 Cycle(边双/判奇偶环)
  5. spark集成kerberos
  6. CTF SSTI(服务器模板注入)
  7. 大数据应用期末总评(hadoop综合大作业)
  8. 《恶魔人crybaby》豆瓣短评爬取
  9. jmeter BeanShell断言(三)数据处理
  10. SpringBoot MAVEN编译报错Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.0: