Shell脚本中的杀戮过程

7 linux shell

我有一个非常简单的问题:当我运行shell脚本时,我启动一个在无限循环中运行的程序.过了一会儿,我想先停止这个程序,然后才能再次使用不同的参数.现在的问题是如何在执行程序时找出程序的pid?基本上,我想做那样的事情:

echo "Executing app1 with param1"  
./app1 param1 &  
echo "Executing app1"  
..do some other stuff  
#kill somehow app1
echo "Execution of app1 finished!"
Run Code Online (Sandbox Code Playgroud)

谢谢!

Rya*_*ght 15

在大多数shell(包括Bourne和C)中,您在后台启动的最后一个子进程的PID将存储在特殊变量$!中.

#!/bin/bash
./app1 &
PID=$!
# ...
kill $PID
Run Code Online (Sandbox Code Playgroud)

"特殊变量"部分下有一些信息.


sth*_*sth 5

在bash中$!扩展为在后台启动的最后一个进程的PID.所以你可以这样做:

./app1 param1 &
APP1PID=$!
# ...
kill $APP1PID
Run Code Online (Sandbox Code Playgroud)