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:32

if you want to find out the PID of a process, you can use ps:

[user@desktop ~]$ ps h -o pid -C app1

the parameter -o pid says that you only want the PID of the process, -C app1 specifies the name of the process you want to query, and the parameter h is used to suppress the header of the result table (without it, you'd see a "PID" header above the PID itself). not that if there's more than one process with the same name, all the PIDs will be shown.

if you want to kill that process, you might want to use:

[user@desktop ~]$ kill `ps h -o pid -C app1`

although killall is cleaner if you just want to do that (and if you don't mind killing all "app1" processes). you can also use head or tail if you want only the first or last PID, respectively.

and a tip for the fish users: %process is replaced with the PID of process. so, in fish, you could use:

user@desktop ~> kill %app1
查看更多
登录 后发表回答