Killing process in Shell Script

2019-03-20 15:39发布

I have a very simple problem: When I run a shell script I start a program which runs in an infinite loop. After a while I wanna stop then this program before I can it again with different parameters. The question is now how do I find out the pid of the program when I execute it? Basically, I wanna do something like that:

echo "Executing app1 with param1"  
./app1 param1 &  
echo "Executing app1"  
..do some other stuff  
#kill somehow app1
echo "Execution of app1 finished!"

Thanks!

标签: linux shell
7条回答
我只想做你的唯一
2楼-- · 2019-03-20 16:11

I had a problem where the process I was killing was a python script and I had another script which was also running python. I did not want to kill python because of the other script.

I used awk to deal with this (let myscript be your python script): kill ps -ef|grep 'python myscript.py'|awk '!/awk/ && !/grep/ {print $2}'

Might not be as efficient but I'd rather trade efficiency for versatility in a task like this.

查看更多
手持菜刀,她持情操
3楼-- · 2019-03-20 16:15

In most shells (including Bourne and C), the PID of the last subprocess you launched in the background will be stored in the special variable $!.

#!/bin/bash
./app1 &
PID=$!
# ...
kill $PID

There is some information here under the Special Variables section.

查看更多
不美不萌又怎样
4楼-- · 2019-03-20 16:17
pidof app1
pkill -f app1
查看更多
【Aperson】
5楼-- · 2019-03-20 16:27

you obtain the pid of app1 with

ps ux | awk '/app1/ && !/awk/ {print $2}'

and then you should be able to kill it....(however, if you've several instances of app1, you may kill'em all)

查看更多
姐就是有狂的资本
6楼-- · 2019-03-20 16:28

In bash $! expands to the PID of the last process started in the background. So you can do:

./app1 param1 &
APP1PID=$!
# ...
kill $APP1PID
查看更多
做个烂人
7楼-- · 2019-03-20 16:29
killall app1
查看更多
登录 后发表回答