Bash 在变量中存储命令 PID 并终止进程
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29340087/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Bash store command PID in variable and kill process
提问by ogs
I would like to use a shell script in order to establish ethernet connection.
我想使用 shell 脚本来建立以太网连接。
I am using a function implemented as :
我正在使用一个实现为的函数:
function connec()
{
ip link set eth0 up
sleep 5
udhcpc -i eth0
pid=$$
echo $pid
ps
kill -9 $pid
}
However, the script returns :
但是,脚本返回:
743
743 root 2704 S {script.sh} /bin/bash ./script.sh connect
767 root 2200 S udhcpc -i eth0
Killed
I don't succeed in store 767 rather than 743. I also tried by using $! but in that specific case "echo $pid" returns 0.
我在商店 767 而不是 743 中没有成功。我也尝试使用 $! 但在这种特定情况下,“echo $pid”返回 0。
回答by paxdiablo
$$
is the currentprocess which means the script is killing itself. You can get the process ID of the last process you started in the background, with $!
but it appears you're not actually starting one of those.
$$
是当前进程,这意味着脚本正在杀死自己。您可以获得在后台启动的最后一个进程的进程 ID,$!
但看起来您实际上并没有启动其中一个。
With your code segment:
使用您的代码段:
udhcpc -i eth0
pid=$$
the pid=
line will only be executed when udhcpc
exits (or daemonises itself, in which case neither $$
nor $!
will work anyway), so there's zero point in trying to kill of the process.
该pid=
行只会在udhcpc
退出时执行(或守护进程本身,在这种情况下既$$
不会也$!
不会工作),因此尝试终止进程是零点。
To run it in the background and store its process ID, so you can continue to run in the parent, you could use something like:
要在后台运行它并存储其进程 ID,以便您可以继续在父进程中运行,您可以使用类似的方法:
udhcpc -f -i eth0 &
pid=$!
and you're using -f
to run in foreground in that case, since you're taking over the normal job control.
-f
在这种情况下,您使用在前台运行,因为您正在接管正常的作业控制。
Or, alternatively, since udhcpc
can create its ownPID file, you can use something like:
或者,由于udhcpc
可以创建自己的PID 文件,您可以使用以下内容:
udhcpc -i eth0 -p /tmp/udhcpc.eth0.pid
pid=$(cat /tmp/udhcpc.eth0.pid)