一、背景
嵌入式Linux无pkill命令。调试时,需要频繁重启app程序,每次都是手动top查看pid,再手动kill,过于繁琐。遂编写调试脚本,可以gdb调试、启动、杀死、重启。
其中重点介绍使用进程名称杀死进程和调试脚本编写。
二、基本原理
ps查找所有进程状态,grep筛选目标进程信息,awk筛选进程pid字段。
三、命令
1.最终命令
kill $(ps -ef|grep test_app|grep -v "grep"|awk '{print $1}')
2.命令分解
$(ps -ef|grep test_app|grep -v "grep"|awk '{print $1}') //查找进程PID
ps -ef //列出所有进程状态
grep test_app //列出包含test_app关键字的进程(此处有两条test_app本身和grep进程)
grep -v "grep" //剔除grep进程
awk '{print $1}' //取第一个参数pid号
3.分解命令执行结果
ps -ef|grep test_app
1307 root [test_app]
9345 root grep test_app
ps -ef|grep test_app|grep -v "grep"
1307 root [test_app]
ps -ef|grep test_app|grep -v "grep"|awk '{print $1}'
1307
四、脚本
1.调试脚本
#!/bin/sh
case "$1" in
-g) #gdb调试
printf "gdb test_app\n"
gdbserver 192.168.8.115:2001 test_app
;;
-s) #启动app进程
printf "start test_app process\n"
/app/test_app &
;;
-k) #杀死app进程
printf "kill test_app process\n"
kill $(ps -ef|grep test_app|grep -v "grep"|awk '{print $1}')
;;
-r) #重启app进程
printf "restart test_app process\n"
/app/debug.sh -k
/app/debug.sh -s
;;
*) #提示信息
echo "Usage: $1 { -g(gdb) | -s(start) | -k(kill) | -r(restart) }"
exit 1
esac
exit $?
2.脚本命令
sh debug.sh -g #启动gdb调试
sh debug.sh -s #启动test_app进程
sh debug.sh -k #杀死test_app进程
sh debug.sh -r #重启test_app进程
五、总结
1.使用进程名称杀死进程一般步骤
a、ps列出所有进程
b、grep查找指定进程
c、grep -v排除grep进程
d、awk获取目标字段(目标进程pid)
e、kill杀死进程